Careeroza
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