Skip to content Skip to sidebar Skip to footer

How To Execute A Dynamic Number Of Criteria In Mongoose.find?

As an example, at any given runtime, Books = { CatSelect : ['SciFi', 'Humor', 'History'], MinPages : [300,50,500] }; If I manually write the query in the find function as b

Solution 1:

You can build up your query object programmatically, based on the selections. For example:

var selections = [0, 1];
var query = { $or: [] };
for (var i=0; i<selections.length; i++) {
  var selection = selections[i];
  query.$or.push({ 
    Category: Books.CatSelect[selection], 
    Pages: { $gte: Books.MinPages[selection] } 
  });
}
MyCollection.find(query).exec(function(err, result){
  //...
}

Post a Comment for "How To Execute A Dynamic Number Of Criteria In Mongoose.find?"