MongoDB / mongoose-发布保存挂钩未运行

Chr*_*odz 2 javascript mongoose mongodb node.js

我有这个模型/模式:

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;
Run Code Online (Sandbox Code Playgroud)

辅助功能:

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);
      }
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

以及调用帮助程序功能的路由器端点:

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
      });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

这里的问题是.post('save'),尽管遵循了说明,但是钩子仍然没有运行,即.save()在模型上使用而不是.findOneAndUpdate例如。我已经挖掘了一段时间,但我看不出这里可能是什么问题。

Invite文件(S)被保存到数据库就好了这样的钩子应该开火,但没有。任何想法可能有什么问题吗?

Dav*_*nte 5

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

  • 那没有什么意义……但是现在可以了;非常感谢,您救了我。 (3认同)