相对简单的场景:
我有这个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.
更多推荐
无法将$ match运算符用于具有ObjectId的mongodb/mongoose聚合
发布评论