Mongoose聚合方法不起作用

时间:2016-01-27 10:30:28

标签: node.js mongodb mongoose aggregation-framework

我有以下几行:

            Score.find({gameId : gameId}).exec(function(err,obj){
                console.log("find length : " + obj.length);
            });

            Score.aggregate([
                {$match: {gameId: gameId}}
            ], function (err, result) {
                console.log('result is : ' + JSON.stringify(result));
                console.log('is there any error : ' + err);
            });

这些行的输出是

result is : []
is there any error : null
find length : 1

我不明白,为什么聚合的“匹配”方法不能按预期工作 - 查找匹配属性的所有文档。我添加Score.find与相同的“正文”,以找出,如果该文件确实存在,它确实存在。

PS:{gameId: gameId} - 第一个gameId是属性的名称,第二个是带有我正在寻找的ID的字符串值。

PS2:流畅的api具有相同的结果:

            Score.aggregate().match({gameId: gameId}).exec(function (err, result){
                console.log('result is : ' + JSON.stringify(result));
                console.log('is there any error : ' + err);
            });

2 个答案:

答案 0 :(得分:2)

您应该将gameId字符串转换为mongodb ObjectId

在mongoose中

mongoose.Types.ObjectId(gameId)

mongodb native way

new ObjectId(gameId)

答案 1 :(得分:0)

请尝试以下代码:

Agency.aggregate([
{
  $match: {
    cid: ObjectId(req.params.cid),
    createdAt: {
      $gte: new Date(req.query.startDate),
      $lt: new Date(req.query.endDate)
    }
  }
},
{
  $group: {
    _id: {
      day: {$dayOfMonth: "$createdAt"},
      month: {$month: "$createdAt"},
      year: {$year: "$createdAt"}
    },
    count: {$sum: 1}
  }
}
]).then(function (result) {
  return res.json(result);
}, function (error) {
  return res.status(500).send(error);
});