mongoose聚合方法不起作用
我有这些行:
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
添加到相同的“body”中以查明。
PS: {gameId: gameId}
– 第一个gameId是属性的名称,第二个是我正在寻找的ID的string值。
PS2:stream利的API有相同的结果:
Score.aggregate().match({gameId: gameId}).exec(function (err, result){ console.log('result is : ' + JSON.stringify(result)); console.log('is there any error : ' + err); });
您应该将gameIdstring转换为mongodb ObjectId
在mongoose
mongoose.Types.ObjectId(gameId)
mongodb原生方式
new ObjectId(gameId)
请尝试下面的代码:
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); });