Mongoose 中间件后更新不起作用 [英] Mongoose middleware post update not working

查看:59
本文介绍了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);
  }
});

我尝试了预更新并且它有效:

I tried pre update and it works:

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

但我想要的是发布更新:

But what I wanted is post update:

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?");,这是预期的吗?

I am not seeing the log console.warn('results', "is this called?");, is this expected?

附:机器:Windows 10,猫鼬版本:4.5.8

p.s: Machine: windows 10, mongoose version: 4.5.8

推荐答案

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

Going by the docs, it looks like you should only have one argument in the schema.post's callback function that represents the document that was updated. It's likely that your callback is never being invoked by the hook because it's never supplied the rest of the arguments. e.g:

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

代替:

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

这篇关于Mongoose 中间件后更新不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆