Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Validation and Middleware

Mongoose Query and Aggregate Middleware

Use Mongoose query middleware for find, update and delete: apply default filters, set updatedAt, handle document versus query hooks and aggregate hooks.

Document hooks fire when you call save() on a document. But most reads and many writes go through queries (find, updateOne, deleteMany) that never create a document at all. Mongoose has a separate set of query middleware for these, plus hooks for aggregations and for insertMany. This lesson shows what they are, how this differs, and the patterns that make them worth using: default filters, automatic fields and cleanup.

Query hooks

In a query pre hook, this is the query (not a document), so you can change the filter, options and projection before the query executes:

JavaScript
const postSchema = new mongoose.Schema({
  title: String,
  status: { type: String, default: 'draft' },
  deletedAt: { type: Date, default: null },
});

postSchema.pre('find', function () {
  this.where({ deletedAt: null });
});

postSchema.pre('findOne', function () {
  this.where({ deletedAt: null });
});

Query hook names match the method: find, findOne, findOneAndUpdate, findOneAndDelete, updateOne, updateMany, deleteOne, deleteMany, countDocuments, replaceOne, and so on. You can register one hook for several using an array or a regular expression:

JavaScript
postSchema.pre(/^find/, function () {   // find, findOne, findOneAndUpdate, ...
  this.where({ deletedAt: null });
});

Useful methods on the query inside a hook:

Call Returns
this.getFilter() the current filter object
this.getUpdate() the update document (update queries)
this.getOptions() the options passed
this.where({...}), this.setOptions({...}) change the query
this.model the model
this.set(...) / this.setUpdate(...) change the update

Post hooks receive the result: postSchema.post('find', function (docs) { ... }), and post('findOneAndUpdate', function (doc) { ... }) gets the document or null.

Pattern 1: a default filter

The soft-delete filter above is the classic use: every read hides deleted data, and one place defines it. Provide an escape hatch through an option, since admin screens need to see everything:

JavaScript
postSchema.pre(/^find/, function () {
  if (this.getOptions().withDeleted !== true) {
    this.where({ deletedAt: null });
  }
});

await Post.find();                                   // hides deleted
await Post.find().setOptions({ withDeleted: true }); // shows everything

Be aware that aggregate pipelines do not use query hooks, so a $match for deletedAt must be added through an aggregate hook (below), or your reports will include deleted data.

Pattern 2: set a field on every update

JavaScript
postSchema.pre(['updateOne', 'updateMany', 'findOneAndUpdate'], function () {
  this.set({ updatedAt: new Date() });
});

(If you use the timestamps option, Mongoose does this for you. The hook just shows the technique.)

Pattern 3: transform input of update queries

JavaScript
userSchema.pre('findOneAndUpdate', async function () {
  const update = this.getUpdate();
  if (update.$set?.password) {
    update.$set.password = await bcrypt.hash(update.$set.password, 12);
  }
});

This is how you keep the "always hash passwords" rule when updates bypass save(). Notice the care required: the update can contain the field at the top level, inside $set, or not at all, so read the shape defensively.

Node.js A query hook that adds a default filter (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.

Document versus query hooks

Some names exist for both forms: updateOne, deleteOne, validate... and by default deleteOne and updateOne hooks are query hooks, with this as the query. To hook the document method (doc.deleteOne()), pass { document: true, query: false }:

JavaScript
schema.pre('deleteOne', { document: true, query: false }, function () {
  console.log('deleting document', this._id);   // this is the document
});

schema.pre('deleteOne', { document: false, query: true }, function () {
  console.log('deleting with filter', this.getFilter());  // this is the query
});

Choosing wrongly gives the confusing situation where the hook never seems to run. When a hook is silent, check which form your code calls.

Also note that hooks on findOneAndDelete do not run for deleteMany; there is one hook per method. For cascades on deleteMany, you can read the filter in a pre, find the ids and remove children, or avoid the problem by using soft deletes and a cleanup job.

Node.js Document hook versus query hook (reference 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.

Aggregate middleware

Aggregation pipelines (later chapter) have their own hook. this is the Aggregate object, and this.pipeline() returns the stages array:

JavaScript
postSchema.pre('aggregate', function () {
  this.pipeline().unshift({ $match: { deletedAt: null } });
});

Putting the $match first keeps it index-friendly. If a pipeline begins with a stage that must come first (such as $geoNear), insert after it instead.

insertMany middleware

insertMany does not run save hooks. It has its own:

JavaScript
schema.pre('insertMany', function (docs) {
  for (const doc of docs) doc.slug = doc.title.toLowerCase().replaceAll(' ', '-');
});

The hook receives the array of documents (in newer versions as plain objects before casting, so read the Mongoose documentation for your version if the order of casting matters).

Putting hooks to work: a checklist

Rule Hook
Hide soft-deleted data pre(/^find/) + pre('countDocuments') + pre('aggregate')
Stamp updates pre on update methods (or the timestamps option)
Hash passwords pre('save') and pre('findOneAndUpdate')
Clean up children post('deleteOne', { document: true, query: false })
Normalize bulk imports pre('insertMany')

Common mistakes

  • Using this as a document in a query hook (it is the query).
  • Forgetting that aggregation ignores query hooks.
  • Registering pre('deleteOne') and expecting it to run for doc.deleteOne().
  • Using arrow functions, losing this.
  • Heavy work in hooks that run on every read; keep read hooks light.
  • Hooks that mutate shared state or call other queries without care, causing infinite loops (a hook on find that calls find).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

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

    Query middleware runs with this set to the query, so you can modify the filter and options.
  2. 2. How do you make pre('deleteOne') run for doc.deleteOne() instead of Model.deleteOne()?

    deleteOne hooks are query hooks by default. The options object selects the document form.
  3. 3. Which hook should you use to add a $match stage to every aggregation?

    Aggregations do not trigger query hooks. pre('aggregate') exposes the pipeline.
  4. 4. What does a pre(/^find/) hook with a deletedAt filter implement?

    The regular expression matches find, findOne, findOneAndUpdate and similar, so one hook hides deleted data everywhere.

Summary

  • Query middleware (find, updateOne, deleteMany, ...) runs with this as the query, letting you add filters, set updates and read options.
  • Use a regular expression such as /^find/ to cover many methods; offer an option to bypass default filters.
  • deleteOne and updateOne hooks are query hooks by default; pass { document: true, query: false } for the document form.
  • Aggregations use pre('aggregate'), and insertMany has its own pre('insertMany').
  • Later chapters build on these: relations with population, aggregation pipelines, indexes, testing and projects continue in the track overview.

Next: References and populate()