Stop 07 · Mongoose ODMTopics · 6/8

Mongoose Middleware (Hooks)

Part of the MERN Stack Roadmap

In short

Some things must happen every single time, like hashing a password before it's saved. Put that in a hook and no controller can ever forget it.

pre and post hooks run code before or after events like save, validate or findOneAndDelete. A common use is hashing a password in a pre('save') hook.

The jaadu, in a security uniform, waves a hand scanner over suitcases rolling along a conveyor belt at an airport checkpoint.

Think of it like this

The airport security check

Every bag goes through the scanner before boarding (pre hook), whoever the passenger is. After landing, every bag gets a tag at the belt (post hook). Passengers don't have to remember. The airport does it automatically.

Watch it happen

What happens on user.save()

save() called
validate
pre('save')
write to MongoDB
post('save')

1/5A controller creates a user with a plain password and calls save().

The big ideas

What you need to know

Document hooks

save and validate hooks run on documents, with this pointing to the document.

Query hooks

find, findOne, findOneAndUpdate and others run on queries, with this pointing to the query.

Updates skip save hooks

findByIdAndUpdate does not trigger pre('save'). Password changes should use save() or a query hook.

Use async functions

Write hooks as async functions. Throwing an error inside stops the operation and passes the error up.

See it in code

Walk through the code

js
1import bcrypt from "bcrypt";2 3const userSchema = new Schema({4  name: String,5  email: { type: String, unique: true },6  password: { type: String, required: true, minLength: 8, select: false },7  deletedAt: Date,8});9 10// Hash only when the password is new or changed11userSchema.pre("save", async function () {12  if (!this.isModified("password")) return;13  this.password = await bcrypt.hash(this.password, 12);14});15 16// Hide soft-deleted users from every find query17userSchema.pre(/^find/, function () {18  this.where({ deletedAt: null });19});20 21userSchema.post("save", function (doc) {22  console.log("User saved:", doc._id.toString());23});

1/4select: false keeps the hash out of query results unless you ask with .select("+password").

A classic pair: hash passwords on save, and filter out soft-deleted users on every find.

Save yourself the pain

Common mistakes

Oops

Using an arrow function for a hook and finding this is undefined.

Do this instead

Use a regular function (or async function) so Mongoose can bind this to the document or query.

Oops

Hashing the password on every save, even when the user only changed their name.

Do this instead

Check this.isModified("password") first and return early.

Your mission

Secure user model

~30 min

Quick check

You update a password with User.findByIdAndUpdate(id, { password }). Why is it stored in plain text?

Go deeper

  1. 1Hash the password in pre('save') only when it has been modified.
  2. 2Delete a post's comments in a hook when the post is deleted.
  3. 3Learn which hooks run for save versus updateOne, since they differ.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge