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.