Skip to content
tezvyn:

Mongoose Middleware (Hooks): Intercepting Database Operations

Source: mongoosejs.comMediumHow cards are made

Mongoose Middleware (Hooks): Intercepting Database Operations

Mongoose middleware (hooks) lets you intercept database operations. Think of them as "before" or "after" scripts for actions like save or find. Use them to hash passwords before saving a user.

Why it exists

Middleware was created to centralize logic related to a data model. Instead of scattering business logic like validation or data transformation across your application, you can attach it directly to the schema, ensuring it runs consistently whenever a specific database operation occurs.

The mental model

Think of Mongoose middleware as event listeners for your database. You're telling Mongoose: "Before you save this document, run my password hashing function," or "After you delete this user, run my function to remove their associated posts." It lets you hook into the lifecycle of a model's operations to inject custom, automated behavior.

How it works

You define middleware on a schema using schema.pre() for "before" hooks and schema.post() for "after" hooks. The first argument is the name of the operation to intercept (e.g., 'save', 'findOne', 'deleteOne'). The second is a function that receives control. Mongoose has four types of middleware: document, query, aggregate, and model. The type determines the context of this. For save middleware (document), this is the document itself. For findOneAndUpdate middleware (query), this is the query object.

When to use it

Use middleware for tasks that should always happen for a given operation. Three common uses: first, hashing passwords before saving a user document; second, updating denormalized data in other collections when a document changes; third, implementing cascading deletes, like removing a user's blog posts when the user document is deleted.

When not to use it

Avoid middleware for one-off logic that only applies in specific controller actions; that logic belongs in your application's service layer. Be especially careful with query middleware like findOneAndUpdate. Since this refers to the query and not the document, you cannot directly access the document's fields, a common point of confusion and bugs. For updateOne and deleteOne, you must explicitly opt-in to get document middleware behavior.

One canonical example

A classic use case is hashing a user's password. On a User schema, you would add a pre('save') hook. This function checks if the password field has been modified. If it has, it generates a salt, hashes the password, and replaces the plain-text password on the document (this.password) with the hashed version. The actual save operation then proceeds with the secured data, ensuring no plain-text passwords ever touch the database.

Interview question

Which scenario best illustrates an appropriate use of Mongoose middleware?

  • a.Applying unique business logic to a document based on a specific user's role in a single API call.
  • b.Ensuring a user's password is consistently hashed before being stored in the database.Correct
  • c.Bypassing Mongoose's built-in validation for performance optimization during bulk inserts.
  • d.Directly accessing and modifying a document's properties within a findOneAndUpdate query hook.
Why?

The card explicitly states that hashing passwords before saving a user document is a canonical use case for middleware, as it ensures this critical step always occurs. Option D is incorrect because the card warns that in query middleware like findOneAndUpdate, 'this' refers to the query object, not the document, making direct document field access problematic.

Just read this? Test yourself on what you have been reading.

Read the original → mongoosejs.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles