复杂的猫鼬过滤器查询 [英] Complex Mongoose Filter Query

查看:32
本文介绍了复杂的猫鼬过滤器查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个网站,允许用户使用侧边栏过滤结果.他们选择的条件越多,他们的搜索结果就越具体(见附图).

I'm building a site that allows users to filter results using a sidebar. The more criteria they select, the more specific their search results should be (see attached image).

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

Users can select filters (checkboxes) that match what they're looking for. I'm using MongoDB for this. My schema is as follows:

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
  }

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

Right now, I'm using a .find() with an $or query but this isn't correct, namely because the $or returns all the matches for any of these criteria. I need the results to filter/narrow down the more criteria I include.

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

See my current code below:

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":[]}

推荐答案

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

You can create a query variable to keep what field will be use to filter.

示例:

var query = {};
var payload = {"brands":["ACWELL","BOTANIC FARM"],"skincareConcerns":[],"productTypes":["essence","moisturizer"],"ingredients":[],"skinType":[]};
if (payload.brands && payload.brands.length > 0) query.brandName = {$in : payload.brands};
if (payload.skincareConcerns && payload.skincareConcerns.length > 0) query.skincareConcern = {$in : payload.skincareConcerns};
if (payload.productTypes && payload.productTypes.length > 0) query.productType = {$in : payload.productTypes};
if (payload.ingredients && payload.ingredients.length > 0) query.ingredients = {$in : payload.ingredients};
if (payload.skinTypes && payload.skinTypes.length > 0) query.skinTypes = {$in : payload.skinTypes};
var result = await Products.find(query);

这篇关于复杂的猫鼬过滤器查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆