davidgtonge / underscore-query

MongoDB like query api for JavaScript Arrays

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

multiple "and" clauses on query built programmatically

claywhipkey opened this issue · comments

I have a search tool project where there are a variable amount of search inputs. When results are filtered it needs to reflect the specs of all the search inputs. In my app I am looping through the input values and trying to construct the final query that will be passed in. I have tried to create a JSON object to pass into your .query() function, but multiple $and keys is invalid and I can't produce the result without manually typing it out (which I can't do because it is dynamic). For example:

var query = _.query(obj.paValues, {
                         "$and": {"attribute_id": 2422, "type": "max", "display_value": {$lte: 200, $gte: 0.3}},
                         "$and": {"attribute_id": 2421, "type": "typ", "display_value": {$lte: 150, $gte: 50}}
                         });

That works fine. But I can't dynamically create that JSON of clauses to pass in.

I would try using the .build() chain API, but I would need to first have a constructor object and then in the loop append .add() queries. When I tried this, it did not work. Here is the attempt:

var queryChain = _.query.build( obj.paValues );
                        queryChain.add("attribute_id",2422);
                        var result = queryChain.run();

In that example, queryChain is not an instance that has the .add() function.

The other problem is I can't seem to make my .and() query include multiple properties at once. I need the clause to group them together. If attribute 20 and 21 have a display_value of 500, I can't just look for the display_value to be 500, I need it to be 500 for a specific attribute. Not sure if this is possible with the chain API anyway.

Any ideas?

$and: should be an array not an object (mongodb will throw an error if you give it an object). Just append to the $and array all your extra queries