复杂的猫鼬过滤器查询
我正在构建一个网站,允许用户使用侧边栏过滤结果.他们选择的条件越多,他们的搜索结果就越具体(见附图).
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);