Mongoose不返回聚合函数的数据

时间:2018-06-10 16:11:52

标签: mongodb mongoose aggregate

我的路线使用以下功能来总结注册的总收入。它在shell和Studio3T中运行良好,但是mongoose API不会返回任何内容。

我正在运行mongoose 5.0.17并使用Azure Cosmos DB。

exports.getDhashboard = function (req, res) {
  Registration.aggregate({
    $group: {
      _id: "$challenge.name",
      totalAmount: { $sum: "$amount" },
      count: { $sum: 1 }
    }
}, function (err, registrations) {

    if (err)
      res.send(err);
    res.json(registrations);
  });
};

以下是来自注册集合的一些示例JSON。

{
        "modified": "2018-06-09T15:43:02.288Z",
        "_id": "5b1bf5863ace0d3f54be45b4",
        "paymentState": "approved",
        "paymentTimeStamp": "2018-06-09T15:43:02.000Z",
        "paymentId": "PAY-1J368604337116737LMN7K3I",
        "payPalBuyerEmail": "kameron.berget-buyer@theitfc.com",
        "payPalBuyerId": "TTJC5ZWWEF9E6",
        "address1": "1 Main St",
        "city": "San Jose",
        "state": "CA",
        "zip": "95131",
        "paymentMethod": "paypal",
        "paymentStatus": "VERIFIED",
        "amount": 20,
        "user": "",
        "__v": 0
    },
    {
        "modified": "2018-06-10T14:58:49.422Z",
        "_id": "5b1d3ca9d586d4697021c128",
        "paymentState": "approved",
        "paymentTimeStamp": "2018-06-10T14:58:46.000Z",
        "paymentId": "PAY-0D492814K5815962PLMOTZCQ",
        "payPalBuyerEmail": "",
        "payPalBuyerId": "TTJC5ZWWEF9E6",
        "address1": "1 Main St",
        "city": "San Jose",
        "state": "CA",
        "zip": "95131",
        "paymentMethod": "paypal",
        "paymentStatus": "VERIFIED",
        "amount": 20,
        "user": "",
        "__v": 0
    }

1 个答案:

答案 0 :(得分:0)

您正在使用旧版本的聚合...使用聚合管道作为对象数组有新的语法。

exports.getDhashboard = function (req, res) {
  Registration.aggregate([
    { $group: {
        _id: "$challenge.name",
        totalAmount: { $sum: "$amount" },
        count: { $sum: 1 }
    }}
  ], function (err, registrations) {
    if (err)
      res.send(err);
    res.json(registrations);
  });
};

您可以看到docs了解更多