Mongoose Middleware

also called pre and post hooks

Document middleware

Document middleware is supported for the following document functions.

  • init

  • validate

  • save

  • remove

pre middleware

schema.pre('init', function(doc) {

});
schema.pre('validate', function(doc) {

});
schema.pre('save', function(doc) {

});
schema.pre('remove', function(doc) {

});

post middlwware

Sample

Query Middleware

Query middleware is supported for the following Model and Query functions.

  • count

  • find

  • findOne

  • findOneAndRemove

  • findOneAndUpdate

  • update

if you wanted to add an updatedAt timestamp to every update() call, you would use the following pre hook.

Last updated