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 below, it works as intended and finds the books with number of pages greater than the indicated amounts in indicated categories.

MyCollection.find({ $or: [ { Category: Books.CatSelect[0], Pages : { $gte: Books.MinPages[0] } }, { Category: Books.CatSelect[1], Pages : { $gte: Books.MinPages[1] } } ] }).execFind(function(err,result){

But the problem is I would not know how many of the categories will be selected, the above example is set .find example for 2 categories.

How to put a varying number of criteria dynamically into the .find function?

Naturally I can put all the criteria in a string, but query is not a string nor a JSON, so I'm kinda lost.

Problem courtesy of: branthor


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];
    Category: Books.CatSelect[selection], 
    Pages: { $gte: Books.MinPages[selection] } 
MyCollection.find(query).exec(function(err, result){
Solution courtesy of: JohnnyHK


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.