Open In App

Mongoose Schemas Instance methods

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB, designed to work in a Node.js environment. One of the key features of Mongoose is its ability to define instance methods on schema objects, which allow you to perform operations on individual documents. This guide will explore Mongoose schema instance methods, how to create them, and provide practical examples to get you started.

What are Mongoose Schema Instance Methods?

In Mongoose, instance methods are functions that are defined on a schema and are available on individual document instances. These methods allow you to interact with or manipulate data in a document, such as retrieving related documents, updating fields, or performing custom business logic.

Instance methods are typically used when we need to work with individual documents, and they are called directly on the document instance. These methods can be either built-in or custom, depending on the use case.

Why Use Mongoose Instance Methods?

  • Encapsulation: Instance methods allow us to encapsulate logic related to a specific document. For example, finding documents of a similar type based on the current document’s type.
  • Code Reusability: With instance methods, you can define reusable functions that operate on individual documents, reducing code duplication.
  • Simplify Query Logic: Instance methods can simplify query operations that involve the document's fields, making the code more readable.

How to Define Instance Methods in Mongoose

Instance methods are defined on the methods object of a Mongoose schema. These methods can then be accessed by creating instances of the model. Below is the syntax to define instance methods:

Syntax

const schema = new mongoose.Schema({

field1: { type: String },

field2: { type: String }

}, {

methods: {

methodName: function() {

// Define the functionality for the instance method

}

}

});

Creating node application And Installing Mongoose

Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y

Step 2: After creating the ReactJS application, Install the required module using the following command:

npm install mongoose

Project Structure: It will look like the following.

 

Example 1: Custom Mongoose Instance Method to Find Similar Document Types

In this example, we'll create a custom instance method that finds documents of the same type as the current document. We will define an Animal schema with a method to find animals of the same type.

Filename: main.js

const mongoose = require('mongoose')

// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));

const animalSchema = new mongoose.Schema(
{ name: String, type: String }, {

// Assign a function to the "methods" object of our
// animalSchema through schema options.
// By following this approach, there is no need to
// create a separate TS type to define the type
// of the instance functions.
methods: {
findSimilarTypes(cb) {
return mongoose.model('Animal').find(
{ type: this.type }, cb);
}
}
}
);

const Animal = mongoose.model("Animal", animalSchema);

const animals = [
{
name: 'bond',
type: 'dog'
},
{
name: 'cavine',
type: 'cat'
}
]

const dog = new Animal({ type: 'dog' });

Animal.insertMany(animals, (err, res) => {
dog.findSimilarTypes((err, dogs) => {
console.log(dogs);
});
})

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output: 

Explanation: In this example, the custom instance method findSimilarTypes finds all animals with the same type as the current document (dog).

Example 2: Custom Mongoose Instance Method to Find "Cat" Documents

In this example, we create another instance method to find all documents with the type "cat". The process is similar to Example 1, but this time we search for cats.

Filename: main.js

const mongoose = require('mongoose')

// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));

const animalSchema = new mongoose.Schema({ name: String, type: String }, {

// Assign a function to the "methods" object
// of our animalSchema through schema options.
// By following this approach, there is no need
// to create a separate TS type to define the type
// of the instance functions.
methods: {
findSimilarTypes(cb) {
return mongoose.model('Animal').find({ type: this.type }, cb);
}
}
}
);

const Animal = mongoose.model("Animal", animalSchema);

const animals = [
{
name: 'bond',
type: 'dog'
},
{
name: 'cavine',
type: 'cat'
}
]

const cat = new Animal({ type: 'cat' });

Animal.insertMany(animals, (err, res) => {
cat.findSimilarTypes((err, cats) => {
console.log(cats);
});
})

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

Explanation: In this example, the instance method findSimilarTypes retrieves all animals with the same type as the current document (cat).

Best Practices for Using Mongoose Instance Methods

  1. Avoid Business Logic in Controller: Keep business logic (such as querying related data) within the model instance methods instead of placing it in your controllers for better organization and maintainability.
  2. Leverage Callbacks or Promises: Mongoose instance methods return a query, so use callbacks or promises to handle the results asynchronously.
  3. Optimize Queries: Ensure that your instance methods return only the data that is necessary, optimizing the query for performance.

Conclusion

Mongoose schema instance methods are a powerful feature that allow us to encapsulate business logic directly within the model, making your code cleaner and easier to maintain. Whether you're querying similar documents or performing custom transformations on a document, instance methods offer a flexible way to handle individual document operations in MongoDB. By following the examples and best practices outlined in this article, you'll be able to create more efficient and maintainable applications using Mongoose instance methods.


Next Article

Similar Reads