无法将 $match 运算符用于带有 ObjectId 的 mongodb/mongoose 聚合 [英] unable to use $match operator for mongodb/mongoose aggregation with ObjectId

查看:33
本文介绍了无法将 $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 类型对象 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 聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆