node.js - $match mongodb聚合框架_mongoose中的多条件
问题描述
我的控制器中有多个查询条件,如果存在我需要路径。
条件 1:
{ tags: mongoose.Types.ObjectId(req.params.tagId)}
条件2:
{ reportedBy: { '$ne': req.user._id }} // if this video object reported dont show
条件3:
{ owner: { '$ne': userblocks } } // userblocks is a array of objectIds
所以这是我的 $match 过滤器:
{
'$match':
_.isString(req.params.tagId) ?
{ tags: mongoose.Types.ObjectId(req.params.tagId),
reportedBy:{ '$ne': req.user._id}, owner: { '$ne': userblocks}}:
{ reportedBy:{ '$ne': req.user._id},owner: {'$ne': userblocks}}
},
如果tagId传递给 params,我使用...扩展运算符。此 条件适用于 tagId,但其他条件不起作用。
随着@Anthony Winzlet 的提示,我试图:
{reportedBy:{ '$ne': mongoose.Types.ObjectId(req.user._id)},owner: {'$ne': userblocks}}
userblocks是一个对象列表,我检查了它们的类型,它们也是对象。所以不需要将它们强制转换为 objectIds。
解决方案
尝试这样的事情:
let $match = {
reportedBy: { '$ne': mongoose.Types.ObjectId(req.user._id) },
owner: { '$nin': userblocks } // $nin when comparing against array of object ids
},
if(_.isString(req.params.tagId)) {
$match.tags = mongoose.Types.ObjectId(req.params.tagId)
}
然后只需$match
在您的aggregation pipeline
或您将拥有的管道的任何其他部分中使用。
注意事项:
- 比较时
_id
mongoose.Types.ObjectId
应该使用函数。 - 当与数组进行比较时,
$in
或者$nin
通常是您想要使用的。 - 在您的
_.isSting
检查逻辑中,您似乎在这两种情况下都有reportedBy
,owner
所以在我看来,一些重构不会受到伤害。
推荐阅读
- javascript - 为数字而不是字符串工作的对象的顺序数组
- amazon-web-services - 无效资源和格式错误的策略错误 - aws cloudformation YAML
- kubernetes - K8s getting error after change gcloud sdk location on Macos
- javascript - 如何在html文件中使用函数调用
- javascript - 如何计算不同日期的 24 小时格式的两个时间之间的差异?
- c - 如何找到正确的括号顺序?
- css - 在 iFrame 中的内容上应用 CSS
- c# - ICommandHandler 未针对 SaveCommandArgs 执行(Visual Studio for Mac 扩展)
- localhost - 如何列出在不同端口上运行的所有进程/服务
- scala - Breeze - DenseVector 的比较给了我一个 BitVector - 这是故意的吗?