I have this document:
{
"_id": ObjectId("xxx"),
"props": {
"a": "a1",
"b": "b2"
}
}
My query looks like this:
db.collection.find({"$and": [ {"props.a" : "a1"}, {"props.b": "b2"} ]}
I get the elements of the query from GET values:
/api/search?a=a1&b=b1
So, I need a way to generate dinamically my query starting from the GET object...
I thought about something like this:
// Little helper to get the object key name by index
Object.prototype.key = function key(int) { var j = -1; for(var i in this) { j++; if(j==int) { return i; } else { continue; } } }
// My attempt
var query = [],
i = 0;
_.each(req.query, function(prop) {
var key = req.query.key(i);
query.push({"props." + key: prop});
i = i + 1;
});
But it does not work...
if I do:
_.each(req.query, function(prop) {
var key = {};
key.properties = {};
key.properties[req.query.key(i)] = prop ;
props.push(key);
i = i + 1;
});
I get this:
[{ props: { a: 'a1' } }, { props: { b: 'b1' } } ]
but in this way I could get only this query:
db.collection.find({"$and": [ { props: { a: 'a1' } }, { props: { b: 'b1' } } ]}
which is completely different from the one I've written above (this one search for a props which is exactly like the ones I've provided, instead the original looks for one which contains one of the values)
how can I do?
Ok I've found a solution, searching on google did not returned any solutions...
var query = {"$and": []},
props = [],
i = 0;
_.each(req.query, function(prop) {
var key = {};
key["properties." + req.query.key(i)] = prop ;
props.push(key);
i = i + 1;
});
query.$and = props;
In this way the query generated is exactly like I need it.