Q13: What are Mongoose Pre and Post Middleware hooks?

Middleware (also called hooks) are functions passed execution control during document operations.

  • Pre Hooks: Run before an event executes (e.g., hashing password before pre('save')).
  • Post Hooks: Run after an event completes (e.g., sending welcome emails after post('save')).
Pre-Save Password Hashing Middleware
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 10);
});
💡 Intercepts document save events to hash passwords conditionally before writing.
Key Takeaways
  • Supported hook types: Document, Query, Aggregate, Model.
  • Commonly used for password hashing, auditing, and cascading cleanups.
Knowledge Check

Inside a document pre('save') middleware function, what does 'this' refer to?