Saturday, October 25, 2025
HomeLanguagesJavascriptMongoose Aggregate.prototype.catch() API

Mongoose Aggregate.prototype.catch() API

The Aggregate API.prototype.catch() method of the Mongoose API is used to perform aggregation tasks. It allows us to execute the query returned promise. It only takes or handle rejected handler. It can be used with asynchronous function more efficiently.

Syntax:

aggregate(...).catch( callback_function )

Parameters: This method accepts a single parameter as discussed below:

  • callback: This is a callback function. It is used to handle the rejected handler.

Return Value: This method returns promise which can be resolved through document or can be rejected through error. 

Setting up Node.js application:

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: 

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Example 1: In this example, we have established a database connection using mongoose and defined model over cricketerSchema, having three columns or fields “_id”, “name”, and “nationality”. At the end, we have defined an asynchronous function named catchExample, and catch() is responsible for handling the returned rejected promise.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const cricketerSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    nationality: String
});
  
const Cricketer = mongoose.model('Cricketers', cricketerSchema);
  
const catchExample = async () => {
    const result = await Cricketer
        .aggregate([{ $group: "$nationality" }])
        .catch(err => {
            console.log('Rejected Handler - ', err)
        })
    console.log(result)
}
catchExample();


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

node app.js

Output:

Rejected Handler -  MongoServerError: a group's fields must be specified in an object

Example 2: In this example, we have established a database connection using mongoose and defined model over cricketerSchema, having three columns or fields “_id”, “name”, and “nationality”. At the end, we have defined an asynchronous function named catchExample2. In this example, as no error is being returned or the promise has not been rejected we are able to see the result set, output variable is responsible for holding the result set.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const cricketerSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    nationality: String
});
  
const Cricketer = mongoose.model('Cricketers', cricketerSchema);
  
const catchExample2 = async () => {
    const output = await Cricketer
        .aggregate([{ $project: { name: 1, nationality: 1 } }])
        .catch(error => {
            console.log('Catch Rejected Handler - ', error)
        })
    console.log(output)
}
catchExample2();


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: 3, name: 'Ben Stokes', nationality: 'England ' },   
  { _id: 2, name: 'David Warner', nationality: 'Australia' },
  { _id: 5, name: 'Aaron Finch', nationality: 'Australia ' },
  { _id: 7, name: 'K L Rahul', nationality: 'India ' },      
  { _id: 6, name: 'Hardik Pandya', nationality: 'India ' },  
  { _id: 1, name: 'Virat Kohli', nationality: 'India' },     
  { _id: 4, name: 'Rohit Sharma', nationality: 'India ' }    
]

Reference: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-catch

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS