【发布时间】:2017-05-21 14:41:18
【问题描述】:
我有一个函数应该返回在给定时间段内创建的用户计数,并按受邀和非受邀分组。在$cond 运算符上,我需要比较字段tkbSponsor 是否不是null 并且不等于example@example.com。如果此条件为真,则该用户被邀请。否则,他没有被邀请。
var countByPeriod = function(req,res) {
var initialDate = req.body.initialDate;
var finalDate = req.body.finalDate;
User.aggregate([
{
"$match": {
"timeStamp": {
"$gte": new Date(initialDate),
"$lt": new Date(finalDate)
}
}
},
{
"$group": {
"_id": null,
"total": { "$sum": 1 },
"invited": {
"$sum": {
"$cond": [
{
"tkbSponsor": {
"$nin": ["example@example.com",null]
}
},
1,
0
]
}
}
}
}
], (err,result) => {
if (!err) {
if (result.length) res.send(result[0]);
else res.send({"total": 0,"invited":0});
} else {
res.sendStatus(500);
console.log(err);
}
});
};
顺便说一句,这个函数在执行时给我一个错误:
{ [MongoError: invalid operator '$nin']
name: 'MongoError',
message: 'invalid operator \'$nin\'',
ok: 0,
errmsg: 'invalid operator \'$nin\'',
code: 15999 }
只是一个观察。我以前使用$cond操作符如下,因为我不需要和null比较:
"$cond": [
{
"$ne": ["$tkbSponsor", "example@example.com"]
},
1,
0
]
而且它有效。但是,现在我还必须比较 tkbSponsor 是否不为 null 并且使用 $nin 是否会给我这个错误。
【问题讨论】:
标签: node.js mongodb mongoose database