这应该是一个简单的问题-我是mongodb的新手,但我仍然对此感到困惑。在nodeJS中的相同查询在aggegate中返回0,但在shell中似乎没问题
在mongodb中,我有一个捐款集合
/* 1 */
{
"_id" : ObjectId("5b9b625c0ffcdb7c339a8961"),
"username" : "abc@xyz.com",
"amount" : 500,
"badge" : true,
"addedAt" : 1536909914979.0,
"first_name" : "john",
"last_name" : "Doe",
"email" : "abc@xyz.com"
}
/* 2 */
{
"_id" : ObjectId("5b9b62e00ffcdb170b9a8962"),
"username" : "abc@xyz.com",
"amount" : 5000,
"badge" : false,
"addedAt" : 1536910048238.0,
"first_name" : "John",
"last_name" : "Doe",
"email" : "abc@xyz.com"
}
在mongodb shell中测试查询,结果符合预期:
db.getCollection('donations').aggregate([
{
'$group' : {
'_id' : null,
'total_donations' : {'$sum' : "$amount"}
}
}
])
结果:
/* 1 */
{
"_id" : null,
"total_donations" : 5500
}
在NodeJS中,我有:
connectToDb(dbUri).then(function (db) {
db.collection('donations').find().sort(sorting).limit(limit).toArray(function (err, arr) {
if (err) {
console.log(err)
res.status(500).json({
message: "Failed to fetch donations"
}).end();
} else {
var allDonations = {};
var query = [
{
'$group' : {
'_id' : null,
'total_donations' : {'$sum' : "$amount"}
}
}
];
db.collection('bottles').aggregate(query).toArray(function(err, result){
if(err) console.log(err);
allDonations['total_donations'] = result[0].total_donations;
allDonations['donations'] = arr;
console.log(allDonations);
});
}
});
结果[0] .total_donations返回为0 我在这里想念的东西吗?
更新1
如安东尼在评论中所建议,我已将代码更改为以下代码:
connectToDb(dbUri).then(function (db) {
var query = [
{
'$group' : {
'_id' : null,
'total_donations' : {'$sum' : "$amount"}
}
}
];
db.collection('bottles').aggregate(query).then(result => {
console.log(result);
})
.catch(error =>{
console.log(error);
});
});
但是现在我得到以下错误:
(node:16708) UnhandledPromiseRejectionWarning: TypeError: db.collection(...).aggregate(...).then is not a function
warning.js:18