Usage of Mongoose Custom Methods and Statics


Usage of Mongoose Custom Methods and Statics

Mongoose is a powerful Node.js library that offers flexibility and functionality in processes working with MongoDB. Often, defining a schema alone is not enough; reusable functions are needed in projects. This is where Mongoose custom methods and statics come into play. In this post, I will share detailed information and examples about "Usage of Mongoose Custom Methods and Statics".

What are Mongoose Custom Methods?

Custom methods allow you to operate on instances (documents) generated from a schema. In other words, when you create a document object, you can add special functions to this object thanks to a custom method. This practical method reduces code repetition and allows you to create more readable data operations.

Defining and Using Custom Methods


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

userSchema.methods.isValidPassword = function(password) {
  // In a real application, a hash comparison should be made
  return this.password === password;
};

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

// Usage
async function login() {
  const user = await User.findOne({ name: 'admin' });
  if (user && user.isValidPassword('1234')) {
    console.log('Login successful!');
  } else {
    console.log('Invalid login!');
  }
}

Here, the isValidPassword function works only on a User document (instance).

What are Mongoose Statics?

Statics are functions belonging to the model level. In other words, they are called directly on the model and are mostly used to operate on multiple documents at once or across the whole database. With Mongoose custom statics, you can create functions mostly for bulk operations or special queries.

Creating and Using Static Methods


userSchema.statics.findByName = function(name) {
  return this.find({ name });
};

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

// Usage
async function listAdmins() {
  const admins = await User.findByName('admin');
  console.log(admins);
}

The findByName function here is called from the model object (User) and returns all users with the relevant name.

Conclusion and Tips

As we have seen in the article titled "Usage of Mongoose Custom Methods and Statics", in Mongoose, we can produce our own helper methods both on schema and model basis using custom methods and statics. Thanks to this structure, code quality and maintainability increase; as projects grow, it becomes possible to write reusable, meaningful, and organized code. By using custom methods and statics in your projects, you can take your code one step further.