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

schema.post('init', function(doc) {
  console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
  console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
  console.log('%s has been saved', doc._id);
});
schema.post('remove', function(doc) {
  console.log('%s has been removed', doc._id);
});

Sample

// create model
var PersonSchema = new Schema(..);
PersonSchema.pre('save', function(next) {
  // do stuff
  next();
});
module.exports = mongoose.model("Person", PersonSchema);

// using model
var newPerson = new Person( { 
    firstName: {type: String, default: ‘Anonymous User’}, 
    lastName: ‘Doe’ 
}); 

// Save ->  Default Applied -> Validation -> Error
newPerson.save(function (err) { 
    if (err) return handleError(err); 
    // saved the person document! 
});

Query Middleware

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

  • count

  • find

  • findOne

  • findOneAndRemove

  • findOneAndUpdate

  • update

schema.pre('find', function() {
  console.log(this instanceof mongoose.Query); // true
  this.start = Date.now();
});

schema.post('find', function(result) {
  console.log(this instanceof mongoose.Query); // true
  // prints returned documents
  console.log('find() returned ' + JSON.stringify(result));
  // prints number of milliseconds the query took
  console.log('find() took ' + (Date.now() - this.start) + ' millis');
});

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

schema.pre('update', function() {
  this.update({},{ $set: { updatedAt: new Date() } });
});

Last updated

Was this helpful?