MongoDB/Mongoose - "Post save"钩子未运行

4

我有这个模型/架构:

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;

辅助函数:
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);
      }
    });
  });
};

路由器端点调用辅助函数:

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')钩子没有运行,尽管遵循了指示,即在模型上使用.save()而不是.findOneAndUpdate。我已经挖掘了一段时间,但看不出这里可能出现的问题。 Invite文档已经成功保存到数据库中,因此钩子应该触发,但实际上并没有。有什么想法吗?
1个回答

11

您可以使用不同数量的参数声明后置钩子。使用3个参数处理错误,因此只有在出现错误时才会调用后置钩子。 但是,如果您的钩子只有1或2个参数,则它将在成功时执行。第一个参数将是保存在集合中的文档,第二个参数(如果传递)是下一个元素。 有关更多信息,请查看官方文档:http://mongoosejs.com/docs/middleware.html 希望能帮助到您。


8
那根本没有任何意义...但现在它能用了 ;S 非常感谢,你救了我。 - Chrillewoodz
这是否意味着,如果我选择不指定一个带有3个参数的回调函数的钩子,那么我的带有2个参数的回调函数的钩子将被跳过,并且常规处理程序将被调用并出现错误?例如,如果保存时发生错误,该错误是否会直接传递给.save(cb)的回调函数? - Will Brickner
如果您在回调函数中声明了带有2个参数的钩子,它只会在成功时执行,而不是在发生错误时执行。可能您可以同时声明两个钩子,一个带有2个参数用于成功处理,另一个带有3个参数用于处理错误。这是一个很好的测试 :) - David Vicente

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接