首页 > 解决方案 > mongodb 中的 $sum 在 NodeJS 中返回 0

问题描述

这应该是一个简单的问题 - 我是 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

标签: node.jsmongodbgroup-bysumaggregate

解决方案


推荐阅读