Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

node.js - Complex Mongoose Filter Query

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...