Mongoose Query.prototype.catch() API
Last Updated :
03 Jun, 2025
Mongoose is an essential Object Data Modeling (ODM) library for MongoDB, providing a straightforward way to interact with MongoDB in Node.js environments. One of the most important features in handling MongoDB queries in Mongoose is error handling.
The Query.prototype.catch()
method is part of Mongoose's powerful promise-based API, and it allows you to handle errors in asynchronous operations effectively. In this article, we will discuss the catch() method in Mongoose, how it works, and give examples of managing errors in Mongoose queries using the catch() method.
What is the Mongoose Query.prototype.catch() Method?
The Mongoose Query API.prototype.catch() method of the Mongoose API is used on the Query objects. With this method, we can manage the rejected promise error and can show it or use it for subsequent processes. If the promise is unsuccessful, the catch() method enables you to catch the exception and handle it appropriately, for instance, by logging the error or implementing a fallback strategy. When a query operation is unsuccessful (e.g., because of invalid data, network connectivity, or MongoDB server exceptions), catch() prevents the error from interrupting the application's flow.
Syntax:
promiseObject.catch( reject );
Parameters
- reject: A callback function that is invoked when the promise is rejected. This callback will receive the error as its parameter.
Return Value
- This method returns promise which can be handled using callback function.
Setting Up Node.js and Mongoose for Error Handling
To get started with using the catch()
method in Mongoose, first, you need to set up a Node.js application with the Mongoose module.
Step 1: Initialize Your 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
The project structure will look like this:
Database Structure: The database structure will look like this, the following database present in the MongoDB.
Example 1: Handling a Successful Query Without Errors
The below example illustrates the basic functionality of the Mongoose Connection catch() method. In this example, promise has been resolved that is why the code execution has not entered in catch block and we are getting all the documents from the collection.
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 studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
rollNumber: { type: Number, required: true },
});
const StudentModel = connectionObject.model(
'Student', studentSchema
);
StudentModel.find().then(res => {
console.log(res);
}).catch(error => {
console.log('Error', 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("63c2fe2ef9e908eb17f225da"),
name: 'Student1',
age: 25,
rollNumber: 36,
__v: 0
},
{
_id: new ObjectId("63c2fe2ef9e908eb17f225db"),
name: 'Student2',
age: 18,
rollNumber: 65,
__v: 0
},
{
_id: new ObjectId("63c2fe2ef9e908eb17f225dc"),
name: 'Student3',
age: 15,
rollNumber: 36,
__v: 0
}
]
Explanation: In this case, there are no errors, so the catch()
method won't be triggered, and the results of the query will be logged.
Example 2: Handling a Query Error Using catch()
The below example illustrates the basic functionality of the Mongoose Connection catch() method. In this example, promise has been rejected that is why the code execution has entered in the catch block and we are getting the expected error with error message. Mongoose will trigger a CastError because the age
field expects a number, but we will provide a string.
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 studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
rollNumber: { type: Number, required: true },
});
const StudentModel = connectionObject.model('Student', studentSchema);
StudentModel.update(
{ name: "Student1" },
{ age: 'Eight' }
).then(res => {
console.log(res);
}).catch(error => {
console.log('Error', 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:
Error CastError: Cast to Number failed for value "Eight" (type string) at path "age"
Explanation: In this example, Mongoose triggers a CastError because the age
field expects a Number, but we provided the value "Eight"
as a string. The catch()
method catches this error and logs it to the console.
Example 3: Handling Query Errors with Asynchronous Error Handling
In a real-world scenario, it is essential to handle errors asynchronously. This example shows how to use the catch()
method with asynchronous query operations.
Filename: app.js
const mongoose = require("mongoose");
// Set up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Define the schema
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
rollNumber: { type: Number, required: true },
});
const StudentModel = mongoose.model("Student", studentSchema);
// Create an async function to update the student's data
async function updateStudentData() {
try {
await StudentModel.updateOne(
{ name: "Student1" },
{ age: 'Twenty' } // Invalid data
);
} catch (error) {
console.log("Caught Error:", error); // Catch and log the error
}
}
updateStudentData();
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Caught Error: CastError: Cast to Number failed for value "Twenty" (type string) at path "age"
Explanation: In this example, we use the async/await
syntax with the catch()
method. The updateOne()
query will fail because the age
field expects a Number, but we provided "Twenty"
as a string. The error is caught asynchronously and logged in the catch()
block
Conclusion
Mongoose's catch() method is a crucial functionality for catching promise rejections. It ensures the stability of your application by enabling you to catch errors and act accordingly when dealing with MongoDB queries. Whether you have basic queries or intricate asynchronous database operations, the use of catch() guarantees that errors are caught elegantly, stopping them from halting your application's execution.
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