Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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).

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
  }

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

Sample payload:

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

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
894 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Sample:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...