Mongoose Validation and Middleware
9 min read
Validation and Hooks in Mongoose
Mongoose runs validation before saving — if a required field is missing or a value falls outside enum, Mongoose throws a ValidationError before the document touches the database.
Middleware (hooks) let you run logic before or after operations like save, validate, and findOneAndUpdate.
js
import bcrypt from "bcrypt";
const userSchema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true, minlength: 8 }
});
// Pre-save hook: hash password before storing
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 12);
next();
});
// Instance method
userSchema.methods.comparePassword = async function (candidate) {
return bcrypt.compare(candidate, this.password);
};
export const User = mongoose.model("User", userSchema);Mongoose middleware does not run on updateMany or findByIdAndUpdate by default. Either use save() or add { runValidators: true } to the update options.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises