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

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

更多推荐

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

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

发布评论

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

>www.elefans.com

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