Mongoose Schema.prototype.static() Method
Last Updated :
01 Apr, 2025
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
- Optimize Queries: Always ensure your queries are optimized by indexing frequently queried fields. This improves performance, especially when using static methods on large collections.
- Use Promises or Async/Await: Handle asynchronous operations properly by using promises or
async/await
to avoid callback hell and ensure smoother code execution. - Error Handling: Always include error handling in your static methods, especially when performing database queries. This ensures robustness in production applications.
- 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
Similar Reads
Mongoose Tutorial Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
Mongoose Schemas
Mongoose Schemas Creating a ModelMongoose is one of the most popular Object Data Modeling (ODM) libraries for MongoDB, providing schema-based solutions to model our application's data. This allows us to define the structure of documents within a MongoDB collection, including validation, typecasting, and other powerful features that
5 min read
Mongoose Schemas and IndexesMongoose is a powerful Object Data Modeling (ODM) library for MongoDB in a Node.js environment. It provides a straightforward way to interact with MongoDB, including features like schema definition, model creation, and database query handling. One key feature of Mongoose is its ability to create and
5 min read
Mongoose Schemas Instance methodsMongoose 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 Mo
5 min read
Mongoose Schemas IdsMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a
2 min read
Mongoose Schemas VirtualsVirtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive
6 min read
Mongoose Schemas AliasesMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability. Creating node application And Installing Mongoose: Step 1: Create a
2 min read
Mongoose Schemas With ES6 ClassesMongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec
2 min read
Mongoose Schemas Query HelpersMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl
3 min read
Mongoose SchemaTypes
Mongoose Documents
Mongoose Queries
Mongoose QueriesMongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read
Mongoose deleteMany() FunctionThe deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it
4 min read
Mongoose Queries Model.replaceOne() FunctionThe Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameter
3 min read
Find() Method in MongooseThe Mongoose find() method is one of the most widely used methods for querying MongoDB collections in Node.js. It provides a flexible and powerful way to fetch data from your MongoDB database. In this article, we will explore the find() method in detail, its syntax, parameters, and how to implement
5 min read
FindById Method in MongooseThe findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl
4 min read
Mongoose QueriesModel.findByIdAndDelete() MethodThe Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
Mongoose findByIdAndRemove() FunctionMongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i
2 min read
Mongoose QueriesModel.findByIdAndDelete() MethodThe Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
FindOne() Method in MongooseThe findOne() method in Mongoose is one of the most commonly used functions for querying data from a MongoDB database. It provides a simple and efficient way to retrieve a single document that matches a specified query condition. This article will explore how to use the findOne() method, explain its
5 min read
Mongoose findOneAndDelete() FunctionThe findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In
5 min read
Mongoose | findOneAndRemove() FunctionThe findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin
2 min read
Mongoose | findOneAndReplace() FunctionWhen working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace(). This function helps in finding a document and replacing it with a new one. But how exactly
5 min read
Mongoose Queries Model.findOneAndUpdate() FunctionThe Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt
3 min read
Mongoose Document Model.replaceOne() APIThe Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters: Â The Mo
3 min read
updateMany() Method in MongooseIn Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document,
4 min read
Mongoose Queries Model.updateOne() FunctionThe Model.updateOne() function in Mongoose is a powerful method used to update a single document within a MongoDB collection. It allows you to specify the conditions for selecting a document and then provides a way to apply updates to that document. In this article, we will explore how updateOne() w
4 min read
Mongoose Populate
Mongoose Schema API
Mongoose Connection API
Mongoose Document API
Mongoose Model API