Mongoose Middleware (Hooks)
pre("save") hook, EK, document, save, hone, se, PEHLE, RUN, hota hai — jaise, password, ko, HASH, karne, ke, liye, COMMON, USE-CASE, hai. next() call, karके, AGLE, STEP, ko, CONTROL, PASS, kiya, jaata hai.
post hooks, OPERATION, COMPLETE, hone, ke, BAAD, RUN, HOTE, HAIN — LOGGING, NOTIFICATIONS, YA, RELATED, DATA, UPDATE, karne, ke, liye, USEFUL, HAIN.
userSchema.pre("save", async function(next) {
if (this.isModified("password")) {
this.password = await bcrypt.hash(this.password, 10);
}
next();
});
userSchema.post("save", function(doc) {
console.log(`New user created: ${doc.email}`);
});- pre() hooks = operation, se, PEHLE, run, hote, hain (jaise, password, hashing)
- post() hooks = operation, ke, BAAD, run, hote, hain (logging, notifications)
- isModified(), check, karta, hai, ki, field, actually, change, hui, ya, nahi
Document, middleware, (pre/post "save") individual, document, instances, PAR, operate, karta hai. Query, middleware, (pre/post "find", "updateOne") QUERY-LEVEL, operations, PAR, chalta hai — updateMany() se, individual, document, hooks, TRIGGER, NAHI, hote.
Mongoose, mein, ek, SPECIAL, "error, handling, middleware" bhi, hai — jab, EK, previous, middleware, ya, operation, error, throw, karta hai, ISE, (err, doc, next) signature, waale, middleware, se, CATCH, kiya, ja, sakta hai.
userSchema.post("save", function(error, doc, next) {
if (error.code === 11000) next(new Error("Email already exists"));
else next(error);
});