【问题标题】:Mongoose middleware post update not workingMongoose 中间件发布更新不起作用
【发布时间】:2017-06-04 23:30:18
【问题描述】:

没有调用回调,但它应该按照 mongoose 中间件中的记录:

schema.post('update', function(error, res, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'));
  } else {
    next(error);
  }
});

我尝试了预更新,它可以工作:

schema.pre("update", function(next) {
    console.warn('results', "i am called");
    next(new Error("error line called"));
});

但我想要的是发布更新:

schema.post("update", function(error, res, next) {
    console.warn('results', "is this called?");
});

实际模型更新:

MyModel.update({_id : 123}, req.payload, function (err, numberAffected, rawResponse) {
    reply("done!");
});

我没有看到日志console.warn('results', "is this called?");,这是预期的吗?

附注: 机器:windows 10, 猫鼬版本:4.5.8

【问题讨论】:

    标签: node.js mongoose mongoose-middleware


    【解决方案1】:

    通过the docs,看起来您应该在schema.post 的回调函数中只有一个参数来表示已更新的文档。钩子可能永远不会调用您的回调,因为它从未提供其余参数。例如:

    schema.post("update", function(doc) {
      console.log('Update finished.');
    });
    

    代替:

    schema.post("update", function(error, res, next) {
      console.log('Update finished.');
    });
    

    【讨论】:

    • 我会试试这个,但我拥有的 sn-p(带 3 个参数的回调)实际上也来自文档。 mongoosejs.com/docs/middleware.html
    • 很高兴这有效。看起来只有三个参数的回调才会在出现错误时触发。仅当您将第二个作为函数手动调用(用于异步目的)时,两个才会起作用,并且无论如何都会触发。
    • 是的,我没有彻底阅读文档实际上是我的错,但在某些时候,我仍然发现文档的某些部分具有误导性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2019-03-20
    • 2021-01-28
    相关资源
    最近更新 更多