MongoDB / mongoose – 后保存钩不运行

我有这个模型/模式:

const InviteSchema = new Schema({ inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true}, organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Organisation', required: true}, sentTo: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true}, createdAt: {type: Date, default: new Date(), required: true} }); InviteSchema.post('save', function(err, doc, next) { // This callback doesn't run }); const Invite = mongoose.model('Invite', InviteSchema); module.exports = Invite; 

帮手function:

 exports.sendInvites = (accountIds, invite, callback) => { let resolvedRequests = 0; accountIds.forEach((id, i, arr) => { invite.sentTo = id; const newInvite = new Invite(invite); newInvite.save((err, res) => { resolvedRequests++; if (err) { callback(err); return; } if (resolvedRequests === arr.length) { callback(err); } }); }); }; 

和调用helper函数的路由器端点:

 router.put('/organisations/:id', auth.verifyToken, (req, res, next) => { const organisation = Object.assign({}, req.body, { updatedBy: req.decoded._doc._id, updatedAt: new Date() }); Organisation.findOneAndUpdate({_id: req.params.id}, organisation, {new: true}, (err, organisation) => { if (err) { return next(err); } invites.sendInvites(req.body.invites, { inviter: req.decoded._doc._id, organisation: organisation._id }, (err) => { if (err) { return next(err); } res.json({ error: null, data: organisation }); }); }); }); 

这里的问题是.post('save')钩子不能运行,尽pipe遵循指令,例如在模型上使用.save()而不是.findOneAndUpdate 。 我一直在挖掘一段时间,但我不明白这里的问题可能是什么。

Invite文档被保存到数据库中,所以钩子应该会触发,但是不会。 任何想法可能是错的?

你可以用不同数量的参数来声明post钩子。 有了3个参数你就可以处理错误,所以你的post钩子只有在出现错误时才会被调用。 但是,如果你的钩子只有1或2个参数,它将在成功执行。 第一个参数是保存在集合中的文档,第二个参数是下一个元素。 欲了解更多信息,请查看官方文档: http : //mongoosejs.com/docs/middleware.html希望它有帮助。