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)
});