Mongoose middleware post update not working

£可爱£侵袭症+ 提交于 2019-12-11 06:38:16

问题


Callback is not being called, but it should as per documented in mongoose middleware:

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?");
});

The actual model update:

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

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

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


回答1:


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.');
});

instead of:

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


来源:https://stackoverflow.com/questions/41755806/mongoose-middleware-post-update-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!