Mongoose: Middleware, Hooks & Virtuals

🍁 MongoDBLesson 12Intermediate

Mongoose supports middleware hooks (pre and post triggers) executing before save/delete operations, and virtual properties.

1 Pre-Save Hooks and Virtuals
JavaScript — Schema hooks
const bcrypt = require("bcrypt");

# Pre-save hook to hash password fields
userSchema.pre("save", async function(next) {
  if (!this.isModified("password")) return next();
  this.password = await bcrypt.hash(this.password, 10);
  next();
});

# Virtual properties (not saved in database, computed on the fly)
userSchema.virtual("fullName").get(function() {
  return `${this.firstName} ${this.lastName}`;
});
2 Code Challenge
Challenge: Create a Mongoose schema using a pre-save hook that automatically formats a user's email to lowercase before inserting it into the database.