Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Testing and Patterns

Schema Plugins and Reusable Patterns

Write Mongoose plugins to share fields, hooks, methods and statics across schemas - soft delete, audit fields and slugs - plus global plugins, options and a runnable plugin stand-in.

Real projects repeat the same schema features: every model needs createdAt, many need soft deletion, some need a URL slug, all should hide __v in JSON. Copy-pasting this into twenty schemas guarantees drift and bugs. A Mongoose plugin packages such behavior once and applies it with schema.plugin(fn).

What a plugin is

A plugin is just a function that receives a schema (and optional options) and adds to it: paths, indexes, virtuals, methods, statics, query helpers and middleware.

JavaScript
export function auditFields(schema, options = {}) {
  schema.add({
    createdBy: { type: Schema.Types.ObjectId, ref: options.userModel ?? 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: options.userModel ?? 'User' },
  });

  schema.pre('save', function () {
    // this is the document; fill in updatedBy from context set by the caller
    if (this.$locals.userId) {
      this.updatedBy = this.$locals.userId;
      if (this.isNew) this.createdBy = this.$locals.userId;
    }
  });
}

// usage
postSchema.plugin(auditFields, { userModel: 'Account' });

Plugins run when you call .plugin(), so call it before compiling the model with mongoose.model(). A plugin applies to the schema you pass it; to cover every schema at once, register it globally (see below).

A runnable stand-in: plugins as functions over a schema

Without Mongoose we can still show the pattern: a "schema" is an object with fields, methods and hooks, and a plugin is a function that adds to it.

Node.js Plugins add fields, methods and hooks (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.

Statics, methods and query helpers

Three places to put reusable behavior, and a plugin can add any of them:

JavaScript
export function softDelete(schema) {
  schema.add({ deletedAt: { type: Date, default: null, index: true } });

  // instance method: doc.softDelete()
  schema.methods.softDelete = function () {
    this.deletedAt = new Date();
    return this.save();
  };

  // static: Model.restore(id)
  schema.statics.restore = function (id) {
    return this.updateOne({ _id: id }, { $set: { deletedAt: null } });
  };

  // query helper: Model.find().notDeleted()
  schema.query.notDeleted = function () {
    return this.where({ deletedAt: null });
  };
}

schema.methods functions see the document as this; statics see the model; query helpers see the query and are chainable. Use regular function syntax, not arrows, so this is bound by Mongoose.

Soft delete: the details

Soft delete marks a document instead of removing it, so users can undo and audit trails remain. To make it safe you must hide deleted documents from normal reads. Two approaches:

  1. A query helper you remember to call (notDeleted()): explicit but easy to forget.
  2. A pre hook on find, findOne, countDocuments that adds deletedAt: null automatically. This is safer by default but surprises people, and you need an escape hatch (.setOptions({ withDeleted: true })).
JavaScript
schema.pre(/^find/, function () {
  if (!this.getOptions().withDeleted) {
    this.where({ deletedAt: null });
  }
});

Remember aggregation pipelines and populate do not always run query middleware the way you expect, so add { $match: { deletedAt: null } } to pipelines yourself. A unique index like email should be partial ({ deletedAt: null }) so a deleted user's email can be reused (see Indexes in Mongoose).

Node.js Auto-hiding soft-deleted documents (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.

Global plugins and schema options

Apply a plugin to every schema with mongoose.plugin(fn) before defining models. Good candidates: a JSON transform that renames _id to id and drops __v, and pagination helpers.

JavaScript
mongoose.plugin(function toJSONCleanup(schema) {
  schema.set('toJSON', {
    virtuals: true,
    versionKey: false,
    transform(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
      return ret;
    },
  });
});

Be careful with global plugins: they also apply to schemas from libraries. Allow an opt-out, for example schema.options.noCleanup. Mongoose's own timestamps: true option is built in: new Schema({...}, { timestamps: true }) adds createdAt and updatedAt for you, so you do not need a plugin for that.

A slug plugin

A common real plugin turns a field into a URL-friendly unique slug:

JavaScript
export function slugify(schema, { from = 'title', field = 'slug' } = {}) {
  schema.add({ [field]: { type: String, unique: true, sparse: true } });
  schema.pre('validate', async function () {
    if (!this.isModified(from) || this[field]) return;
    const base = String(this[from]).toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    let slug = base, n = 1;
    while (await this.constructor.exists({ [field]: slug })) slug = `${base}-${++n}`;
    this[field] = slug;
  });
}

The check-then-set loop has a race (two requests can pick the same slug), which the unique index catches: retry on error code 11000.

Node.js Slug generation with collisions (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.

Design guidelines

  • Keep a plugin focused on one concern and configurable through options.
  • Document the fields, methods and indexes it adds (createdBy, deletedAt, ...).
  • Add the plugin's index in the plugin so it cannot be forgotten.
  • Test a plugin once on a throwaway schema (see Testing Mongoose code), not in every model.
  • Prefer a plugin to inheritance when models are unrelated but share features; prefer discriminators when documents share a collection and differ by type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a Mongoose plugin?

    Plugins are plain functions (schema, options) applied with schema.plugin().
  2. 2. Where must you call schema.plugin() relative to mongoose.model()?

    The model is compiled from the schema when mongoose.model() runs, so plugins must be applied first.
  3. 3. Why use a partial unique index on email with soft delete?

    Unique among { deletedAt: null } lets a new user take the email of a soft-deleted one.
  4. 4. Why use a normal function (not an arrow) for schema.methods?

    Arrow functions ignore the this that Mongoose sets, so the document would be inaccessible.

Summary

  • A plugin is a function (schema, options) that adds reusable behavior.
  • Plugins can add fields, indexes, methods, statics, query helpers and middleware.
  • Soft delete needs automatic filtering and a partial unique index.
  • mongoose.plugin() applies globally; use it sparingly.
  • Keep plugins small, configurable and tested once.

Next: Transactions and sessions