无法将$ match运算符用于具有ObjectId的mongodb/mongoose聚合
相对简单的场景:
我有这个Voucher
对象,它具有user
属性(类型为ObjectId
).我想获取单个用户的所有凭证值的总和.这是我当前的策略,该策略返回一个空数组:
I have this Voucher
object which has a user
property (of type ObjectId
). I want to get the sum of all voucher values for a single user. Here is my current strategy, which returns an empty array:
Voucher.aggregate [
{ $match : { user : new ObjectId(user_id), expires : { $gt : new Date() } } }
{ $group : { _id : null, sum : { $sum : '$value' } } }
], (err, result)->
console.log err
console.log result
删除user
id的匹配项,并保留expires
字段将返回结果.所以问题就变成了user
上的匹配是什么问题?
Removing the match for the user
id, and leaving the expires
field will return results. So the question becomes what is wrong with the match on user
?
原来,ObjectId的强制转换似乎是问题所在.当它只需要纯ObjectId mongoose.Types.ObjectId
时,就可以使用Schema类型的Object Id mongoose.Schema.Types.ObjectId
进行强制转换.
Turns out the casting of the ObjectId seemed to be the issue. It was being cast using the Schema type Object Id mongoose.Schema.Types.ObjectId
when it needed to be just a pure ObjectId mongoose.Types.ObjectId
.