Pre and Post Hook in Mongoose: What They Are and How They Work
mongoose, pre and post hooks are functions that run before or after certain database operations like saving or deleting data. They let you add custom logic automatically around these actions to control or react to changes.How It Works
Think of pre and post hooks in Mongoose like checkpoints on a road trip. A pre hook is a stop you make before continuing your journey, allowing you to prepare or change something before moving forward. A post hook is a stop after you finish a task, letting you check results or clean up.
In Mongoose, these hooks attach to actions like saving a document or deleting it. The pre hook runs before the action happens, so you can validate data or modify it. The post hook runs after the action, so you can log the event or trigger other processes.
Example
This example shows a pre hook that runs before saving a user to hash their password, and a post hook that logs a message after saving.
const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const userSchema = new mongoose.Schema({ username: String, password: String }); // Pre hook: hash password before saving userSchema.pre('save', async function(next) { if (this.isModified('password')) { this.password = await bcrypt.hash(this.password, 10); } next(); }); // Post hook: log after saving userSchema.post('save', function(doc) { console.log(`User ${doc.username} saved with hashed password.`); }); const User = mongoose.model('User', userSchema); async function run() { await mongoose.connect('mongodb://localhost:27017/testdb'); const user = new User({ username: 'alice', password: 'secret123' }); await user.save(); await mongoose.disconnect(); } run();
When to Use
Use pre hooks when you need to prepare or check data before it is saved or updated, like hashing passwords, validating fields, or setting timestamps. They help keep your data clean and secure automatically.
Use post hooks when you want to react after an operation, such as logging actions, sending notifications, or updating related data. This helps you track changes or trigger side effects without cluttering your main code.
For example, in a blog app, a pre hook can set the publish date before saving a post, and a post hook can update a search index after the post is saved.
Key Points
- Pre hooks run before a database action to prepare or validate data.
- Post hooks run after a database action to react or log results.
- They help keep your code clean by separating side tasks from main logic.
- Commonly used for security (like password hashing) and auditing (like logging).