5

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

Tyro Hunter
  • 755
  • 1
  • 8
  • 20

1 Answers1

12

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.');
});
Pyx
  • 340
  • 2
  • 12
  • I will try this, but the snippet I had (callback with 3 params), was actually from the docs too. http://mongoosejs.com/docs/middleware.html – Tyro Hunter Jan 20 '17 at 05:00
  • 1
    Glad this worked. It looks like a callback with three args will only fire if there is an error. Two will only work if you invoke the second manually as a function (for async purposes) and one will fire no matter what. – Pyx Jan 20 '17 at 05:10
  • yeah it was actually my bad for not reading the docs thoroughly, but at some point, still I find some parts of the doc misleading – Tyro Hunter Jan 20 '17 at 05:18