Mongoose 聚合(Aggregate).then()方法
Mongoose聚合的 then() 方法是用于执行聚合任务的。它允许我们处理聚合方法返回的promise。此 then() 方法在内部调用 .exec() 来执行成功回调函数或错误回调函数。
语法:
aggregate().then(successCallback, errorCallback)
参数: 此方法接受如上所述的两个参数,并在下面描述:
- successCallback: 如果Promise被解析,将执行此回调函数。
- errorCallback: 如果Promise被拒绝,将执行此回调函数。
返回值: 此方法以数组形式返回结果集。
设置Node.js Mongoose模块:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目结构将如下所示:
数据库结构:
数据库结构如下所示,集合中包含以下文档。
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了一个模型,模型包含三列或字段”_id”、”name”和”age”。最后,我们在User模型上调用aggregate方法,并使用then()方法处理返回的promise。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
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)
})
运行程序的步骤: 从项目的根目录下执行以下命令来运行应用程序:
node app.js
输出:
[
{ _id: 1, name: 'Virat Kohli', age: 32 },
{ _id: 2, name: 'David Warner', age: 35 },
{ _id: 3, name: 'Ben Stokes', age: 38 }
]
示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在studentSchema上定义了一个模型,此模型有两个列或字段:“name”和“rollNumber”。最后,我们在User模型上调用 aggregate 方法,并用变量 agg 存储结果,并在 agg 上调用 then( ) 方法来处理Promise。
数据库结构: 数据库结构如下,集合中存在以下文档。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
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)
}
})
运行程序的步骤: 要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
[
{
_id: new ObjectId("63879b6e636d0979693c29f5"),
name: 'Aakash',
rollNumber: 101
},
{
_id: new ObjectId("63879b6e636d0979693c29f6"),
name: 'Rahul',
rollNumber: 102
}
]
参考文献: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-then