首页 > 解决方案 > $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。

标签: node.jsmongodbmongooseaggregation-framework

解决方案


尝试这样的事情:

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检查逻辑中,您似乎在这两种情况下都有reportedByowner所以在我看来,一些重构不会受到伤害。

推荐阅读