Skip to main content

Static Methods in Mongoose

Static Methods in Mongoose | Rustcode

Static Methods in Mongoose

Static methods in Mongoose are functions attached to the Model itself rather than individual document instances. They operate at the collection level, making them ideal for custom queries, aggregations, and utility functions that involve multiple documents. This guide explains how to define and use static methods effectively.


What Are Static Methods?

  • Static methods are functions defined on the schema's statics object.
  • They are accessible on the model class, not on document instances.
  • Used to define reusable methods to perform operations on the entire collection.

Defining Static Methods

Add static methods directly to your schema's statics object:

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

userSchema.statics.findByName = function(name) {
  return this.find({ name: new RegExp(name, 'i') });
};

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

Using Static Methods

Call statics directly on the model:

User.findByName('Alice')
  .then(users => {
    console.log('Users found:', users);
  })
  .catch(err => {
    console.error(err);
  });
  • Static methods return Mongoose queries or promises, suitable for chaining and async/await usage.

Use Cases for Static Methods

  • Complex or commonly used database queries, e.g., filtering users by activity status.
  • Aggregation operations spanning multiple documents.
  • Utility functions that involve the whole collection such as cleaning data or bulk updates.
  • Centralizing query logic to maintain cleaner controller code.

Quick Reference Table

Aspect Description Example
Static Method Function available on the Model class schema.statics.name = function() { ... }
Called On Model (e.g. User.findByName()) User.findByName('John')
Purpose Operations across multiple documents or the whole collection Custom queries, aggregations
Return Query, promise, or any return value Supports async/await

Best Practices

  • Use static methods for logic involving multiple documents or collection-wide operations.
  • Separate static methods from instance methods for clarity and maintainability.
  • Use async/await with static methods where appropriate to handle asynchronous code.
  • Document your static methods well to improve code readability for your team.

Conclusion

Static methods provide a clean way to add reusable, collection-level functions to your Mongoose models. They help in organizing complex queries and operations, improving the maintainability of your codebase. Mastering static methods is essential for building scalable and well-structured MongoDB applications in Node.js.

Comments