Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose middleware post update not working

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

like image 887
Tyro Hunter Avatar asked Feb 06 '23 07:02

Tyro Hunter


1 Answers

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.');
});
like image 199
Pyx Avatar answered Feb 08 '23 10:02

Pyx