Understanding Mongoose Model.exists() API for Efficient Document Search
Last Updated :
09 Jun, 2025
Mongoose, a well-known Object Data Modeling (ODM) library for MongoDB and Node.js. It gives a convenient method of dealing with MongoDB data. One of its critical APIs is the Model.exists() API that facilitates the efficient identification of whether a document exists in a collection by certain conditions. This article delves into the Model.exists() method, its syntax, usage, and examples and assist you in using it efficiently within your Node.js projects.
What is Model.exists()
in Mongoose?
The Model.exists() function in Mongoose provides a function to determine whether there is a minimum of one document in the database that satisfies a certain filter criterion. It serves as a quick means of confirming the presence of documents without retrieving the full document, hence more efficient compared to other functions such as findOne() or find(). The outcome of this approach is a promise that will resolve to an object with the _id of the matching document in case of a match or to null in case of no match
Syntax:
Model.exists()
Parameters:
- filter: It is an object which specifies the condition to select the document from the collection.
- options: It is an object with various properties.
- callback: It is a callback function that will run once execution is completed.
Returns:
- The Model.exists() function returns a promise. The result contains an object with "_id" of the document that matches the filter condition. If not matched it will return null.
Setting up Node.js Application with Mongoose
To demonstrate how Model.exists()
works, follow these steps to set up a simple Mongoose application.
Step 1: Initialize the Node.js Project
Create a Node.js application using the following command:
npm init
Step 2: Install Mongoose
After creating the NodeJS application, Install the required module using the following command:
npm install mongoose
Step 3: Project Structure
Database Structure: The database structure will look like this, the following documents are present in the collection.
Example 1: Using Model.exists()
to Find a Document
In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields "name" and "age". In the end, we are using exists() method on the User model to get the "_id" of the document where the value of "age" field is "20".
app.js:
// Require mongoose module
const mongoose = require('mongoose');
// Set Up the Database connection
mongoose.connect(
'mongodb://localhost:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
})
const userSchema = new mongoose.Schema(
{ name: String, age: Number}
)
// Defining userSchema model
const User = mongoose.model('User', userSchema);
User.exists({age: 20}).then(result => {
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("6316eef52d1b8030ebe17040") }
Explanation: The User.exists({ age: 20 })
query checks if there is a document where the age
field is equal to 20
. If a match is found, it returns the _id
of the document; if not, it returns null
.
Example 2: Using Model.exists()
with Non-Existing Data
In this example, we are providing such value to the "age" field for which the document does not exist in the database. So, in the output, we will get a "null" value.
app.js:
// Require mongoose module
const mongoose = require('mongoose');
// Set Up the Database connection
mongoose.connect(
'mongodb://localhost:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
})
const userSchema = new mongoose.Schema(
{ name: String, age: Number}
)
// Defining userSchema model
const User = mongoose.model('User', userSchema);
User.exists({age: 50}).then(result => {
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:
null
Explanation: The User.exists({ age: 50 })
query checks if there is a document with age
equal to 50
. Since no document matches the filter, the result is null
Conclusion
The Model.exists() method is a quick, effective feature in Mongoose for determining whether documents exist in a MongoDB collection under a filter criterion. As opposed to other methods such as findOne() or find(), exists() is optimized in terms of performance because it only returns the _id of the corresponding document, not the full document. This would be especially convenient if you only want to check if a document exists without necessarily having to fetch its contents.
Similar Reads
Mongoose Document Model() API The Mongoose Document APIModel() method of the Mongoose API is used on the Document model. It allows to create a MongoDB class. Using this method we can create model that can interact with MongoDB for all operations. Let us understand the APIModel() method using an example. Syntax: mongoose.model( d
3 min read
Mongoose Document Model.bulkWrite() API When working with MongoDB and Mongoose in Node.js, handling multiple database operations one by one can be slow and inefficient. Thatâs where the Model.bulkWrite() method comes in handy. This powerful API lets you execute multiple write operations (insert, update, delete, replace) in a single comman
4 min read
Mongoose Document Model.count() API The Model.count() method of the Mongoose API is used to count the number of documents present in the collection based on the given filter condition. It returns the query object and count of documents present in the collection.Syntax:Model.count()Parameters: The Model.count() method accepts two param
2 min read
Mongoose Document Model.countDocuments() API The Model.countDocuments() method of the Mongoose API is used to count the number of document present in a collection. The countDocument() method count the number of documents in a collection based on matching filter. Model.countDocuments() method accepts four parameters: filter:Â It is an object to
3 min read
Mongoose Model.create() API In Node.js applications, Mongoose provides an effective way to interact with MongoDB, allowing developers to define models and schemas to store and retrieve data. One of the essential methods provided by Mongoose is Model.create(), which is used to create one or more documents in a MongoDB collectio
5 min read
Mongoose Document Model.deleteMany() API The Model.deleteMany() method of the Mongoose API is used to delete more than one document in the collection at a time in one go. We can provide an object which contains a condition to the deleteMany() and can be executed on the model object. It will delete all the documents from the collection that
3 min read
Mongoose Document Model.deleteOne() API The Model.deleteOne() method of the Mongoose API is used to delete a document from the collection. We can provide an object of the field to the deleteOne() and can be executed on the model object. It will delete the first document that matches the condition from the collection. Syntax: Model.deleteO
3 min read
Mongoose Document Model.estimatedDocumentCount() API The Model.estimatedDocumentCount() method of the Mongoose API is used to count the number of documents in the MongoDB collection. It is useful for large collections. It is faster than other methods provided by mongoose because it collects metadata instead of scanning the entire collection.Syntax:Mod
2 min read
Mongoose Document Model.events API The Model.events property of Mongoose API is used to return the model's events instance. The instance of the event contains the fields like _events, _eventsCount, and _maxListeners. Syntax: Model_Name.events Return Value: The Model.events property returns the events instance of the model. Setting up
3 min read
Understanding Mongoose Model.exists() API for Efficient Document Search Mongoose, a well-known Object Data Modeling (ODM) library for MongoDB and Node.js. It gives a convenient method of dealing with MongoDB data. One of its critical APIs is the Model.exists() API that facilitates the efficient identification of whether a document exists in a collection by certain condi
4 min read