问题
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