Open In App

Mongoose Aggregate.prototype.catch() API

Last Updated : 07 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads