Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Schemas and Models

Mongoose Instance Methods, Statics and Query Helpers

Add behavior to your Mongoose models with instance methods, static methods and chainable query helpers, plus plugins for sharing logic across schemas.

A model that only holds data soon gets surrounded by helper functions scattered across the codebase: isAdult(user), findByEmail(email), getActive(). Mongoose lets you attach this behavior to the schema itself, so it travels with the model and is easy to find. There are three places to put it, depending on what the code operates on.

Kind Operates on Called on Example
Instance method One document A document user.isAdult()
Static method The model or collection The model User.findByEmail(e)
Query helper A query being built A query User.find().active()

Instance methods

An instance method has access to the document through this. Define it on schema.methods before compiling the model:

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

userSchema.methods.isAdult = function () {
  return new Date().getFullYear() - this.birthYear >= 18;
};

userSchema.methods.greet = function () {
  return `Hello, ${this.name}!`;
};

const User = mongoose.model('User', userSchema);

const u = new User({ name: 'Ada', birthYear: 1990 });
console.log(u.greet());   // 'Hello, Ada!'
console.log(u.isAdult()); // true

Instance methods can be asynchronous and can save the document. A realistic example is a method that checks a password:

JavaScript
userSchema.methods.verifyPassword = async function (plain) {
  return await bcrypt.compare(plain, this.password); // bcrypt is an npm package
};

Always use function, not arrow functions, so that this is the document. You can also define many at once with schema.method({ greet() {...}, isAdult() {...} }), or pass methods in the schema options.

Static methods

A static is a function on the model, useful for logic about the whole collection. Inside it, this is the model:

JavaScript
userSchema.statics.findByEmail = function (email) {
  return this.findOne({ email: email.toLowerCase() });
};

userSchema.statics.countAdults = function () {
  const cutoff = new Date().getFullYear() - 18;
  return this.countDocuments({ birthYear: { $lte: cutoff } });
};

const user = await User.findByEmail('[email protected]');
const adults = await User.countAdults();

Return the query or promise so callers can await it (and, for a returned query, keep chaining).

Query helpers

A query helper adds a chainable method to queries. Define it on schema.query; this is the query:

JavaScript
userSchema.query.active = function () {
  return this.where({ status: 'active' });
};

userSchema.query.byName = function (name) {
  return this.where({ name: new RegExp(name, 'i') });
};

const result = await User.find().active().byName('ada').limit(5);

The difference from a static: User.active() would not work, because a query helper exists on a query, so you start with find(). In return the helper chains with sort, limit and everything else. Use query helpers for reusable filters; use statics for entry points.

Seeing the three kinds side by side

The stand-in below builds a miniature "model" so you can compare how the three kinds are called. It is plain JavaScript, not Mongoose.

Node.js Methods, statics and query helpers (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.

Documents versus lean results

Methods are attached to the model's prototype, so they exist only on hydrated documents. A document loaded with .lean() is a plain object and has no isAdult(). If a function must also work with plain objects, write it as an ordinary function that takes the object as an argument.

Plugins: sharing logic across schemas

When several schemas need the same methods or hooks, write a plugin: a function that receives the schema and adds to it.

JavaScript
function softDeletePlugin(schema) {
  schema.add({ deletedAt: { type: Date, default: null } });

  schema.methods.softDelete = function () {
    this.deletedAt = new Date();
    return this.save();
  };

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

userSchema.plugin(softDeletePlugin);
postSchema.plugin(softDeletePlugin);

You can register a plugin on every schema with mongoose.plugin(fn) before models are compiled. Many npm packages (for pagination, soft delete, auto-increment) are just plugins.

Node.js A plugin adds behavior to any schema (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.

Common mistakes

  • Using arrow functions, which break this.
  • Defining methods after mongoose.model(); the model has already been compiled, so they are not picked up.
  • Calling a query helper on the model instead of a query (User.active()).
  • Forgetting that lean() results do not have instance methods.
  • Overloading a model with business logic that belongs in a service layer; keep methods about the data itself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is called on a single document?

    Instance methods are defined on schema.methods and run with this set to the document.
  2. 2. What is this inside a static method?

    Statics are called on the model, so this is the model and you can call this.find() or this.findOne().
  3. 3. Why does User.active() fail while User.find().active() works for a query helper?

    A query helper is added to schema.query, so it exists on Query objects returned by find().
  4. 4. When must schema.methods functions be defined?

    The model is compiled from the schema at the time of mongoose.model(), so later additions are not included.

Summary

  • Instance methods act on one document, statics act on the model, query helpers add chainable filters to queries.
  • Define them on the schema before compiling the model, and use regular functions so this is correct.
  • Methods do not exist on lean() results.
  • Plugins package shared schema additions (fields, methods, hooks) for reuse across models.

Next: Subdocuments and arrays