【发布时间】:2017-06-17 23:35:28
【问题描述】:
我正在使用mongoose 4.5.0 并尝试使用聚合来获取数据,但它失败了。
这是我的节点代码:-
..
var preMonths = new moment().subtract(4, 'months').date(1).toDate(); //4:for 5 month
var match = { $and: [] };
match.$and.push({ companyId: new ObjectID(req.user.companyId._id) });
match.$and.push({ status: 'CONVERTED' });
var allUnderUsers = [];
req.session.underUser.forEach(function(element, index) {
allUnderUsers.push(ObjectID(element))
});
match.$and.push({ assignTo: { $in: allUnderUsers } });
match.$and.push({ createdOn: { $gt: preMonths, $lt: new moment().toDate() } });
var aggregate = [
{ $match: match }, {
$group: {
_id: { month: { $month: "$date" },year: { $year: "$date" } },
total: { $sum: '$value' }
}
}
];
console.log(JSON.stringify(aggregate))
Lead.aggregate(aggregate)
.exec(function(err, data) {
if (err)
return next(err)
var temp = [];
data.forEach(function(element, index) {
temp.push([moment().month(element._id.month).format('MMM')+' '+element._id.year, element.total]);
})
res.status(200).json(temp)
})
..
这是安慰后的查询字符串:-
> 控制台日志(聚合)
> [{"$match":{"$and":[{"companyId":"5875bb5ba5a2f0e52f76ec6c"},{"status":"CONVERTED"},{"assignTo":{"$in":["587dbf58cab7be105d076516", “587dcd3edca5f235f862fdfd”, “587e1002dca5f235f862fe03”, “587e1079ad90f640757d396a”, “587e1193af725041b6a41a4d”, “587e131faf725041b6a41a58”, “587f1705edf2fa25f0ed1935”, “5881a1ffc51165fbc30a2c60”, “58873cb9ca352ccf80337ccd”]}},{ “createdOn”:{ “$ GT”:“2016-10 -01T09:11:19.357Z","$lt":"2017-02-01T09:11:19.358Z"}}]}},{"$group":{"_id":{"month":{" $month":"$date"},"year":{"$year":"$date"}},"total":{"$sum":"$value"}}}]
现在,这里出现错误:-
{ MongoError: can't convert from BSON type missing to Date 在 Function.MongoError.create (/home/node_modules/mongodb-core/lib/error.js:31:11) 在 插座。 (/home/node_modules/mongodb-core/lib/connection/connection.js:306:22) 在 emitOne (events.js:96:13) 在 Socket.emit (events.js:188:7) 在 readableAddChunk (_stream_readable.js:172:18) 在 Socket.Readable.push (_stream_readable.js:130:10) 在 TCP.onread (net.js:542:20) 名称:'MongoError',消息:'无法从缺少的 BSON 类型转换为日期',确定:0,errmsg: '无法从缺少的 BSON 类型转换为日期',代码:16006,
代号:'Location16006'}
【问题讨论】:
-
从错误“'can\'t convert from BSON type missing to Date'”,你能确定日期值不为空吗
-
是的,日期值不为空这里是日期查询日志
"createdOn":{"$gt":"2016-10-01T09:11:19.357Z","$lt":"2017-02-01T09:11:19.358Z"} -
添加另一个匹配条件以确保您希望属于 Date 类的所有字段实际上都是 Dates。