Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Validation and Middleware

Mongoose Document Middleware: pre and post Hooks

Run code before and after saving with Mongoose pre and post hooks: hashing passwords, setting fields, validate hooks, error handling and hook order.

Middleware (also called hooks) are functions that Mongoose runs automatically before or after certain operations. They let you put cross-cutting logic, such as hashing a password, generating a slug, or writing an audit entry, in the schema instead of repeating it in every route. This lesson covers document middleware, which runs on a single document. The next lesson covers query and aggregate middleware.

pre and post

schema.pre(hookName, fn) runs before the operation. schema.post(hookName, fn) runs after it completes. Register hooks before compiling the model.

JavaScript
const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  slug: String,
  name: String,
});

userSchema.pre('save', async function () {
  console.log('about to save', this.email);
});

userSchema.post('save', function (doc) {
  console.log('saved', doc._id);
});

In a pre hook, this is the document. In Mongoose 5 and earlier you had to call a next() callback; modern Mongoose lets an async function (or a function returning a promise) simply finish, and you may still accept next if you prefer. Throwing an error (or rejecting) stops the operation and rejects the save() promise with that error.

Document hooks available

Hook Runs for
validate doc.validate(), and automatically before save
save doc.save(), Model.create()
updateOne, deleteOne when called on a document with { document: true }
init after a document is loaded from the database

pre('validate') runs before validation and pre('save') runs after validation succeeds, so it is the right place to transform data that must already be valid, and pre('validate') is the place for transformations that validation depends on.

Order of events on save() of a new document:

flowchart TD
  A["doc.save()"] --> B["pre validate hooks"]
  B --> C["validation"]
  C --> D["post validate hooks"]
  D --> E["pre save hooks"]
  E --> F["write to MongoDB"]
  F --> G["post save hooks"]

A failure at any step skips the rest.

Common uses

Hash a password only when it changed

JavaScript
import bcrypt from 'bcrypt'; // npm package, installed on your machine

userSchema.pre('save', async function () {
  if (!this.isModified('password')) return;      // skip if unchanged
  this.password = await bcrypt.hash(this.password, 12);
});

isModified(path) is crucial: without it the hash would be hashed again on every unrelated save. A hook runs for every save(), so check what changed.

Generate a slug and set derived fields

JavaScript
userSchema.pre('validate', function () {
  if (this.isModified('name') || !this.slug) {
    this.slug = this.name.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-');
  }
});

Detect new documents

this.isNew is true before the first insert, so you can run code only on creation, for example sending a welcome email in a post('save') hook after checking a flag you set in the pre hook. Remember that isNew is already false in post('save').

Audit and cascade

JavaScript
postSchema.post('deleteOne', { document: true, query: false }, async function (doc) {
  await Comment.deleteMany({ post: doc._id });   // clean up children
});

The options object chooses whether the hook runs for the document form (doc.deleteOne()), the query form (Model.deleteOne()), or both. This is the most frequent middleware surprise, and the next lesson explains it further.

Seeing the chain

The stand-in below implements a tiny hook runner with pre and post hooks, isModified, and error short-circuiting, so you can watch the order. It is plain JavaScript, not Mongoose.

Node.js pre and post hooks around save (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output shows the password hashed only on the first and third saves, and the invalid document never reaching the write.

Hooks run in registration order

Several pre('save') hooks run one after another in the order you defined them. If the order matters (slug before uniqueness check), define them in that order. Plugins register hooks too, so apply plugins before or after your own deliberately.

Error handling hooks

A post hook with three parameters (error, doc, next) is an error handler: it runs only when an earlier step failed, and is the standard way to turn a MongoDB duplicate key error into a friendlier one:

JavaScript
userSchema.post('save', function (error, doc, next) {
  if (error.name === 'MongoServerError' && error.code === 11000) {
    next(new Error('That email is already registered'));
  } else {
    next(error);
  }
});

An error handler must declare all three parameters, otherwise Mongoose treats it as a normal post hook.

What middleware does not catch

Hooks are a feature of Mongoose, so they are skipped when:

  • you use Model.updateOne/updateMany (query hooks run, document save hooks do not),
  • you use insertMany (it has its own pre('insertMany')),
  • you use bulkWrite or the raw driver (Model.collection),
  • you use lean() and write with the driver.

If a rule must always hold (for example a password must be hashed), do not rely only on a save hook; also enforce it where the data enters, or set up update hooks (next lesson).

Node.js Which operations trigger which hooks (reference table in code)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Using an arrow function, which loses this.
  • Hashing a password on every save because isModified was not checked.
  • Registering hooks after mongoose.model().
  • Expecting pre('save') to run for updateOne or insertMany.
  • Doing slow work (network calls) inside hooks on a hot path.
  • Forgetting that isNew is false inside post('save').

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is this inside a pre('save') hook?

    Document middleware runs with this set to the document, as long as you use a regular function.
  2. 2. Why check this.isModified('password') in a password hashing hook?

    pre('save') runs on every save, so without the check the stored hash would be hashed again.
  3. 3. What happens if a pre hook throws an error?

    An error in a pre hook aborts the operation and rejects its promise.
  4. 4. Which operation does NOT run pre('save') hooks?

    insertMany uses its own pre('insertMany') hook and skips save middleware.

Summary

  • pre hooks run before and post hooks after an operation; register them before compiling the model, with regular functions.
  • On save, the order is validate hooks, validation, save hooks, the write, then post hooks; an error stops the chain.
  • Use isModified and isNew to run logic only when needed (hashing, slugs, welcome actions).
  • Three-parameter post hooks handle errors; hooks are skipped by insertMany, bulkWrite and driver-level writes.

Next: Query and aggregate middleware