无法将 $match 运算符用于带有 ObjectId 的 mongodb/mongoose 聚合

编程入门 行业动态 更新时间:2024-10-23 23:21:13
本文介绍了无法将 $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 聚合

本文发布于:2023-11-22 13:16:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   match   ObjectId   mongoose   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!