Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MongoDB/mongoose-当mongoose中有多个操作预移除钩子时,如何处理下一个调用?_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript MongoDB/mongoose-当mongoose中有多个操作预移除钩子时,如何处理下一个调用?

Javascript MongoDB/mongoose-当mongoose中有多个操作预移除钩子时,如何处理下一个调用?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,这是我目前的预钩: OrganisationSchema.pre('remove', function(next) { Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}, (err) => { if (err) { return next(err); } Invite.remove({or

这是我目前的预钩:

OrganisationSchema.pre('remove', function(next) {

  Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}, (err) => {

    if (err) {
      return next(err);
    }

    Invite.remove({organisation: this._id}, (err) => {

      if (err) {
        return next(err);
      }

      next();
    });
  });
});
这显然不起作用,因为如果没有
Invite
文档,则永远不会调用
next

我想要的最好是:

OrganisationSchema.pre('remove', function(next) {

  Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}, next);
  Invite.remove({organisation: this._id}, next);
});
但此解决方案将触发两次
next
,可能导致应用程序崩溃


在调用
next
之前,是否有一种优雅的方法来等待多个操作完成?我一直在考虑的一个解决方案是使用一个已完成操作的计数器,然后我可以对照操作总数进行检查,但我觉得一定有更好的方法。

您的第一个示例应该可以工作,因为始终调用回调,即使没有
Invite
文档

然而,一种解决方案是使用承诺,因为猫鼬支持承诺:

OrganisationSchema.pre('remove', function(next) {
  Promise.all([
    Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}).exec(),
    Invite.remove({organisation: this._id}).exec()
  ])
    .then(next)
    .catch(next)
});