Open In App

Mongoose Query.prototype.catch() API

Last Updated : 03 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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