Open In App

Mongoose Schema.prototype.static() Method

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

Mongoose is an essential Object Data Modeling (ODM) library for MongoDB in Node.js. It provides powerful tools to interact with MongoDB using a well-defined schema structure. One of the most useful features of Mongoose is its ability to define static methods on schemas, which allows us to perform class-level operations and queries.

What is the Mongoose Schema.prototype.static() Method?

The static() method in Mongoose allows us to define static methods directly on the schema. These methods are called on the model itself and are typically used for operations that need to affect the entire collection, such as custom database queries or aggregations.

Static methods differ from instance methods, which operate on individual document instances. The static() method is used for defining static class methods, which are accessible at the model level (not the instance level).

Why Use Mongoose Static Methods?

  • Reusable Query Logic: Static methods allow us to encapsulate reusable query logic at the model level, making your application more modular and easier to maintain.
  • Custom Database Queries: Static methods make it easier to define complex queries that you can reuse throughout your application.
  • Improved Code Readability: By moving logic related to data retrieval into static methods, your routes and controllers remain clean and readable.

How to Define Static Methods in Mongoose

In Mongoose, static methods are defined on the schema using the static() method. These methods are accessible on the model and can be used to query or manipulate collections.

Syntax:

schemaObject.static( method, callback );

Parameters:

  • method: It is used to specify the method name at the class level for the model.
  • callback: It is used to specify the function which will do the specific task for the method.

Return Value:

The static method can return any value based on your logic. Typically, we would return a Mongoose query or a promise for database operations.

Setting up Node.js Mongoose Module

Step 1: Create a Node.js application using the following command:

npm init

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

npm install mongoose

Project Structure: The project structure will look like this: 

Example 1: Using static() to Find Customers by Address

The below example illustrates the functionality of the Mongoose Schema static() method. In this example, we have defined static method named findCustomerByAddress, we are fetching the document for which the value of address field value is Indore, and we are handling the returned value as a promise using then and catch block.

Filename: app.js

// Require mongoose module
const mongoose = require("mongoose");

// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"

const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const customerSchema = new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
});

customerSchema.static('findCustomerByAddress',
function (address) {
return this.find({ address: address });
})

const Customer =
connectionObject.model('Customer', customerSchema);

Customer.findCustomerByAddress('Indore').then(result => {
console.log(result);
}).catch(error => console.log(error));

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
{
_id: new ObjectId("639ede899fdf57759087a655"),
name: 'Chintu',
address: 'Indore',
orderNumber: 6,
__v: 0
}
]

Explanation: In this example, the static method findCustomerByAddress retrieves all customers with the address “Indore”. This method works at the model level, making it reusable and easy to maintain.

Example 2: Using static() to Fetch All Customer Documents

The below example illustrates the functionality of the Mongoose Schema static() method. In this example, we have defined static method named as getAll, we are fetching all the documents from the database, and we are handling the returned value using anonymous asynchronous function.

Filename: app.js

// Require mongoose module
const mongoose = require("mongoose");

// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"

const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const customerSchema = new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
});

customerSchema.static('getAll', function () {
return this.find({});
})

const Customer =
connectionObject.model('Customer', customerSchema);

(async () => {
const result = await Customer.getAll();
console.log(result);
})();

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
{
_id: new ObjectId("639ede899fdf57759087a655"),
name: 'Chintu',
address: 'Indore',
orderNumber: 6,
__v: 0
},
{
_id: new ObjectId("639ede899fdf57759087a653"),
name: 'Aditya',
address: 'Mumbai',
orderNumber: 2,
__v: 0
},
{
_id: new ObjectId("639ede899fdf57759087a654"),
name: 'Bhavesh',
address: 'Delhi',
orderNumber: 5,
__v: 0
}
]

Explanation: In this example, the static method getAll fetches all customer documents from the database. It is executed using async/await to handle the asynchronous operation in a more readable way.

Best Practices for Using Mongoose Static Methods

  1. Optimize Queries: Always ensure your queries are optimized by indexing frequently queried fields. This improves performance, especially when using static methods on large collections.
  2. Use Promises or Async/Await: Handle asynchronous operations properly by using promises or async/await to avoid callback hell and ensure smoother code execution.
  3. Error Handling: Always include error handling in your static methods, especially when performing database queries. This ensures robustness in production applications.
  4. Keep Queries Reusable: Define static methods for frequently used queries and logic to reduce redundancy in your codebase.

Conclusion

The Mongoose Schema.prototype.static() method is an essential tool for defining static class-level methods in Mongoose models. Static methods are helpful for creating reusable query logic, simplifying your code, and ensuring better maintainability. Whether you are querying documents, aggregating data, or performing other model-level operations, static methods provide an efficient and scalable solution.

By following the examples and best practices outlined in this article, we can effectively use static methods in Mongoose to enhance your application’s data handling and improve code quality



Next Article

Similar Reads