Mongoose Middleware: Pre and Post Hooks
Learners will write document and query middleware hooks for tasks like hashing passwords before save or logging after find.
What Is Mongoose Middleware?
Mongoose middleware (also called hooks) are functions that run before or after specific operations like save, find, updateOne, deleteOne, and more. They enable you to inject custom logic into the lifecycle of document and query operations without cluttering your route handlers. Common uses include hashing passwords before save, logging query times, enforcing soft deletes, and populating related data after find.
Two Types: Document and Query Middleware
Mongoose has two distinct categories of middleware: Document middleware hooks into operations on a specific Document instance (save, validate, remove, init). Query middleware hooks into query operations invoked on the Model (find, findOne, updateOne, deleteOne, etc.). The key difference is what this refers to—in document middleware, this is the document; in query middleware, this is the query object.
// Document middleware: 'this' = the document
userSchema.pre('save', function () {
console.log('Saving document:', this.email);
});
// Query middleware: 'this' = the Query object
userSchema.pre('find', function () {
console.log('Running query:', this.getQuery());
});All lessons in this course
- Connecting With the Official Node.js Driver
- Mongoose Schemas, Models, and Virtuals
- Mongoose Queries, Chaining, and Lean Documents
- Mongoose Middleware: Pre and Post Hooks