Hooks & Populate

Hooks and Populates

๐Ÿ”น 1. Hooks (Middleware)


What are Hooks?

Hooks (middleware) are functions that run before or after certain operations.

Used to add logic automatically
Example: validation, hashing password, logging


๐Ÿ”น Types of Hooks


Pre Hook (before operation)

Runs before saving data

Example:

userSchema.pre("save", function(next) {

this.name = this.name.toUpperCase()

next()

})


Before saving, name becomes uppercase


Post Hook (after operation)

Runs after operation

Example:

userSchema.post("save", function(doc) {
console.log("User saved:", doc)
})



๐Ÿ”น Common Use Cases

  • Password hashing (very important)
  • Validation
  • Logging
  • Auto-updating fields


Simple Understanding

Hooks = automatic functions triggered during DB operations


๐Ÿ”น 2. Populate


What is Populate?

populate() is used to replace a reference (ID) with actual data.

Works like JOIN in SQL


๐Ÿ”น Example Idea

Two collections:

  • users
  • posts

Post document:
userId โ†’ reference to user


๐Ÿ”น Without Populate

Post contains only:
userId: "123abc"


๐Ÿ”น With Populate

Post becomes:
userId โ†’ full user data (name, email, etc.)


๐Ÿ”น Example

Post.find().populate("userId")

Automatically fetches user details


๐Ÿ”น Why Use Populate?

  • Avoid writing complex queries
  • Easily fetch related data
  • Cleaner code


Simple Understanding

  • Hooks โ†’ run logic automatically
  • Populate โ†’ fetch related data