Beginner LevelMongoDB & Mongoose
How do Mongoose Schema Hooks (pre and post middleware) work?
❓ Interview Prompt: Explain Mongoose document and query middleware, pre-hooks (hashing passwords, updating timestamps), and post-hooks.
Mongoose Middleware (hooks) passes control during the execution of asynchronous document and query lifecycle methods:
Common Use Cases:
•
Pre-Save Hook: Hash plaintext passwords with bcrypt before saving to MongoDB.
•
Pre-Update Hook: Automatically update 'updatedAt' timestamps.
•
Post-Hook: Trigger external logging or notifications after successful document persistence.
Code Implementation Example
typescript
import { Schema } from 'mongoose';
import bcrypt from 'bcrypt';
const userSchema = new Schema({ password: String });
// Pre-save hook to hash password before writing to MongoDB
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});💡Pre-save schema hook hashing user password prior to persistence.
🎯 Interview Key Takeaway
Use Mongoose pre-save hooks to encapsulate password hashing and data normalization directly inside schemas.
#Mongoose Hooks#Middleware#pre-save#Beginner
Back to all MongoDB & Mongoose Questions→