it should be a simple issue - I'm new with mongodb , but I'm still stuck on this . Same query in nodeJS returning 0 in aggegate, but seems to be ok in shell
in mongodb I have a donations collection
/* 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"
}
Testing query in mongodb shell, results are as expected:
db.getCollection('donations').aggregate([
{
'$group' : {
'_id' : null,
'total_donations' : {'$sum' : "$amount"}
}
}
])
RESULT:
/* 1 */
{
"_id" : null,
"total_donations" : 5500
}
In NodeJS I have :
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);
});
}
});
The result[0].total_donations here is returning as 0 anything I'm missing here ?
UPDATE 1
As suggested by Anthony in the comments, I have changed the code to below:
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);
});
});
but now i get the following error:
(node:16708) UnhandledPromiseRejectionWarning: TypeError: db.collection(...).aggregate(...).then is not a function
warning.js:18