Discover how to make your database actions smarter and error-free with just a few lines of code!
Why Mongoose middleware (pre/post hooks) in Express? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have to check or change data every time before saving it to your database, or run some cleanup right after deleting a record, and you do this by writing the same code in every place where you save or delete data.
Manually repeating these checks and actions everywhere is tiring, easy to forget, and can cause bugs if you miss a spot. It also makes your code messy and hard to maintain.
Mongoose middleware lets you write these checks or actions once as pre or post hooks on your data models, so they run automatically before or after certain database operations, keeping your code clean and reliable.
await validateUser(user); await user.save(); await logSave(user);
userSchema.pre('save', function(next) { /* validation code */ next(); }); await user.save();This makes your database operations smarter and safer by automating important steps without extra code everywhere.
For example, hashing a password automatically before saving a user, so you never store plain text passwords by mistake.
Manual repetition of checks is error-prone and messy.
Mongoose middleware automates actions before/after database events.
This keeps code clean, consistent, and safer.
Practice
pre middleware in Mongoose?Solution
Step 1: Understand middleware timing
Pre middleware runs before a database action, allowing preparation or validation.Step 2: Differentiate pre and post hooks
Post middleware runs after the action, so pre is for before actions.Final Answer:
To run code before a database operation like save or remove -> Option DQuick Check:
Pre middleware = before action [OK]
- Confusing pre with post middleware
- Thinking pre defines schema structure
- Assuming pre connects to database
Solution
Step 1: Recall Mongoose middleware method names
Mongoose usespreandpostmethods for middleware, notbeforeoron.Step 2: Check syntax for pre-save hook
The correct syntax isschema.pre('save', function(next) { ... next(); });to run code before saving.Final Answer:
schema.pre('save', function(next) { /* code */ next(); }); -> Option BQuick Check:
Use schema.pre for pre hooks [OK]
- Using schema.post instead of schema.pre for pre hooks
- Using non-existent methods like before or on
- Forgetting to call next() in middleware
doc.updatedAt after saving?schema.pre('save', function(next) {
this.updatedAt = new Date();
next();
});Solution
Step 1: Understand pre-save middleware effect
The middleware setsthis.updatedAtto the current date before saving.Step 2: Confirm middleware runs before save
Since it runs before save, the document'supdatedAtwill be updated to the current time.Final Answer:
The current date and time when save is called -> Option CQuick Check:
Pre-save sets updatedAt = now [OK]
- Assuming updatedAt is undefined without schema field
- Confusing createdAt with updatedAt
- Thinking next() is missing causing error
schema.pre('remove', (next) => {
console.log('Removing', this._id);
next();
});Solution
Step 1: Check function type in middleware
Mongoose middleware requires normal functions to bindthisto the document.Step 2: Identify arrow function issue
Arrow functions do not bindthis, sothiswill be undefined inside the middleware.Final Answer:
Arrow function does not bind 'this', so 'this' is undefined inside middleware -> Option AQuick Check:
Use normal functions for middleware to access this [OK]
- Using arrow functions in middleware
- Forgetting to call next() in async middleware
- Thinking remove event is unsupported
Solution
Step 1: Identify when to run logging and cache update
Logging and cache update should happen after saving, so use post middleware.Step 2: Choose correct function syntax
Post middleware receives the saved document as first argument; use normal function to accessthisif needed.Final Answer:
Use schema.post('save', function(doc) { console.log('Saved:', this._id); updateCache(this); }); -> Option AQuick Check:
Post-save + normal function for logging/cache [OK]
- Using pre instead of post for after-save tasks
- Using arrow functions losing this context
- Not passing doc argument in post middleware
