0
0
Expressframework~10 mins

Mongoose middleware (pre/post hooks) in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Mongoose middleware (pre/post hooks)
Define Schema
Attach pre-hook
Attach post-hook
Create Model
Call Model Method (e.g., save)
Run pre-hook
Execute original method
Run post-hook
Return result
This flow shows how Mongoose middleware hooks run before and after a model method like save, allowing code to run around database actions.
Execution Sample
Express
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String });
userSchema.pre('save', function(next) {
  console.log('Before save');
  next();
});
userSchema.post('save', function(doc) {
  console.log('After save', doc.name);
});
This code sets up a schema with pre and post save hooks that log messages before and after saving a user.
Execution Table
StepActionHook TypeHook Function OutputNext Step
1Call user.save()NoneN/ARun pre-save hook
2Run pre-save hookpreLogs 'Before save'Call original save method
3Execute original saveNoneUser saved to DBRun post-save hook
4Run post-save hookpostLogs 'After save <name>'Return from save()
5Return from save()NoneSave completeEnd
💡 All hooks run in order; save completes after post hook.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
user.name"Alice""Alice""Alice""Alice""Alice"
hookLog[]["Before save"]["Before save"]["Before save", "After save Alice"]["Before save", "After save Alice"]
Key Moments - 3 Insights
Why does the pre-hook call next()?
The pre-hook calls next() to tell Mongoose to continue running the original save method. Without next(), the save would stop (see execution_table step 2).
When does the post-hook run?
The post-hook runs after the original save method finishes successfully (see execution_table step 4). It receives the saved document.
Can pre-hooks modify data before saving?
Yes, pre-hooks can change document fields before calling next(), so the saved data can be altered (implied in step 2 before save).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 3?
AThe post-save hook logs a message
BThe pre-save hook logs a message
CThe original save method runs and saves the user to the database
DThe save method returns without saving
💡 Hint
Check the 'Action' and 'Hook Type' columns at step 3 in the execution_table
At which step does the post-save hook log the user's name?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for 'post' hook type and logging action in execution_table step 4
If the pre-hook did not call next(), what would happen?
AThe save method would not run and the user would not be saved
BThe post-hook would run immediately
CThe save method would run twice
DNothing would change
💡 Hint
Refer to key_moments about the importance of calling next() in pre-hooks
Concept Snapshot
Mongoose middleware hooks run code before (pre) or after (post) model methods.
Pre-hooks must call next() to continue the operation.
Post-hooks receive the result after the operation.
Use hooks to add logic around DB actions like save or remove.
Hooks run in order: pre -> original method -> post.
Full Transcript
Mongoose middleware allows you to run code before or after certain model methods like save. You define pre-hooks that run before the method and post-hooks that run after. The pre-hook must call next() to let Mongoose continue saving. The post-hook runs after the save completes and can access the saved document. This lets you add custom logic around database actions easily. The flow is: define schema, attach pre and post hooks, create model, call method, run pre-hook, run original method, run post-hook, then finish. This helps keep your code organized and reactive to data changes.