复杂猫鼬过滤器查询

时间:2019-07-06 17:02:54

标签: node.js mongodb mongoose

我正在建立一个站点,允许用户使用侧边栏过滤结果。他们选择的标准越多,他们的搜索结果就应该越具体(请参见附图)。

用户可以选择与他们要查找的内容匹配的过滤器(复选框)。我为此使用MongoDB。我的架构如下:

brandName: {
    type: String,
    required: false
  },
productType: {
    type: String,
    required: false
  },
  skincareConcern: {
    type: Array,
    required: false
  },
  ingredients: {
    type: Array,
    required: false
  },
  skinType: {
    type: Array,
    required: false
  }

现在,我正在将.find()$or查询一起使用,但这是不正确的,即因为$or返回了所有这些条件的所有匹配项。我需要结果来过滤/缩小我包含的更多条件。

在下面查看我当前的代码:

Products.find({
    $or: [
      { brandName : { $in : brands, $exists: true, $ne: [] } },
      { skincareConcern : { $in : skincareConcerns, $exists: true, $ne: [] } },
      { productType : { $in : productTypes, $exists: true, $ne: [] } },
      { ingredients : { $in : ingredients, $exists: true, $ne: [] } },
      { skinTypes : { $in : skinTypes, $exists: true, $ne: [] } }
    ]
  }

样本有效载荷:

{"brands":["ACWELL","BOTANIC FARM"],"skincareConcerns":[],"productTypes":["essence","moisturizer"],"ingredients":[],"skinType":[]}

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以创建一个查询变量,以保留将用于过滤的字段。

示例:

<script>
  localStorage.setItem("STUDID", "HUMMS-201906");
</script>

答案 1 :(得分:1)

let aggrQuery = [
    {
        '$match': {
            $and: [
                brandName ? { 'brandName ': { $in: brands } } : {},
                skincareConcern ? { 'skincareConcern ': { $in: skincareConcerns } } : {},
                productType ? { 'productType ': { $in: productTypes } } : {},
                ingredients ? { 'ingredients ': { $in: ingredients } } : {},
                skinTypes ? { 'skinTypes ': { $in: skinTypes } } : {}
            ]
        }
    }
]
Products.aggregate(aggrQuery).exec((err, result) => {

})