Open In App

Mongoose Aggregate.prototype.then() API

The Aggregate then() method of the Mongoose API is used to perform the aggregation task. It allows us to handle the promise returned by the aggregate method. This then() method internally calls .exec() to execute either the success callback function or the error callback function.

Syntax:



aggregate().then(successCallback, errorCallback)

Parameters: This method accepts two parameters as mentioned above and described below:

Return Value: This method returns the result set in the form of an array.



Setting up Node.js Mongoose Module:

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 a model over userSchema, having three columns or fields “_id”, “name”, and “age”. At the end, we are calling aggregate method on User model and handing returned promise using then() method.

Filename: app.js




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    age: Number
});
  
const User = mongoose.model('User', userSchema);
  
User.aggregate([{ $project: { _id: 1, name: 1, age: 1 } }])
    .then((successCB, errorCB) => {
        if (successCB)
            console.log(successCB)
        else
            console.log(errorCB)
    })

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: 1, name: 'Virat Kohli', age: 32 }, 
  { _id: 2, name: 'David Warner', age: 35 },
  { _id: 3, name: 'Ben Stokes', age: 38 }   
]

Example 2: In this example, We have established a database connection using mongoose and defined model over studentSchema, having two columns or fields “name”,  and “rollNumber”. At the end, we are calling aggregate method on User model and storing result in a variable named agg and calling then() method on agg to handle the promise.

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

 

Filename: app.js




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: String,
    rollNumber: Number
});
  
const Student = mongoose.model('Student', studentSchema);
  
const agg = Student.aggregate([
    { $project: { name: 1, rollNumber: 1 } }])
  
agg.then((successCB, errorCB) => {
    if (successCB) {
        console.log(successCB)
    }
    else {
        console.log(errorCB)
    }
})

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("63879b6e636d0979693c29f5"),
   name: 'Aakash',
   rollNumber: 101
 },
 {
   _id: new ObjectId("63879b6e636d0979693c29f6"),
   name: 'Rahul',
   rollNumber: 102
 }
]

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


Article Tags :