Mongodb Guide

Pre and Post Hooks in Mongoose

1. Definition

Pre and Post hooks (also called middleware) in Mongoose are functions that run before (pre) or after (post) certain database operations like save, update, delete, etc.

2. Simple Understanding

👉 Pre Hook = runs BEFORE an operation
👉 Post Hook = runs AFTER an operation
👉 Used to add extra logic automatically

3. When to Use

  • Before saving data (validation, hashing password)
  • After saving data (logging, notifications)
  • Before delete/update operations
  • When automating repeated logic

4. Where it is Used

  • Schema definition
  • User authentication systems
  • Logging and auditing
  • Data processing workflows

5. Why We Use It

  • Automates repetitive tasks
  • Improves code reusability
  • Ensures consistency
  • Keeps business logic clean

6. How It Works

  • Defined inside schema
  • Triggered automatically
  • Uses pre() and post() methods
  • Runs based on operation type

7. Basic Syntax

// Pre Hook
schema.pre("save", function(next) {
  console.log("Before saving");
  next();
});

// Post Hook
schema.post("save", function(doc) {
  console.log("After saving", doc);
});

8. Real Example

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: String,
  password: String
});

// Pre hook (before save)
userSchema.pre("save", function(next) {
  console.log("Hashing password...");
  next();
});

// Post hook (after save)
userSchema.post("save", function(doc) {
  console.log("User saved:", doc.name);
});

const User = mongoose.model("User", userSchema);

9. Explanation

  • pre("save") runs before saving document
  • post("save") runs after saving document
  • next() is required in pre hook
  • doc contains saved document in post hook

10. Advantages

  • Automates logic
  • Cleaner code structure
  • Reusable logic
  • Centralized control

11. Disadvantages

  • Can make debugging harder
  • Hidden execution flow
  • Performance overhead if overused

Interview Points

  • Pre = before operation
  • Post = after operation
  • Used for automation and logic
  • Defined in schema