How to access updated document during mongoose post update middleware?
In the Query object you receive in the post hook, you have access to the parameters sent to the query. You can get it like this
_conditions: { id: 'cjauvboxb0000xamdkuyb1fta' }const id = this._conditions.id
this also works on update/updateOne/updateMany
schema.post('update', function (documents) { this.model.find(this._conditions).then(documents => { console.log(documents.length) }})
Schema.post('update')
is only used in error handling (custom error messages)
// The same E11000 error can occur when you call `update()`// This function **must** take 3 parameters. If you use the// `passRawResult` function, this function **must** take 4// parametersSchema.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); }});
If you wanted to add an updatedAt timestamp to every update() call for example, you would use the following pre hook.
Schema.pre('update', function() { this.update({},{ $set: { updatedAt: new Date() } });});