Search code examples
node.jsexpressnode-mongodb-native

How to pass mongodb match conditions from node.js URL parameters


I have a webpage where users selects variables to filter and get database values. I tried passing the $match condition variables as below but i am not getting any results back

URL is : example.com?gender=M&date_from=20100101&date_to=201140101

I loop through the req.query to build the match condition string.

var matchQuery = [];
for (var param in req.query) {
    qString = "{'" + param + "' : '" + req.query[param] + "'}";
    matchQuery.push(qString);              
}
var strmatchQuery = matchQuery.toString();

This outputs strmatchQuery as {'gender' : 'M'}, {'date_from' : '20100101'}, {'date_to' : '20140101'}

and then I call the mongodb aggregate function

dbmodel.aggregate( { $match: { $and: [ strmatchQuery ]} } , { $group : { _id : "$orderyear", totalorders : { $sum : 1 } } } )

But I dont get any results back. Any ideas?


Solution

  • function is_numeric(num) {
        return !isNaN(num);
    }
    
    var matchQuery = [];
    var qString = {};
    for (var param in req.query) {
        // You need objects in your query not strings so push objects
        qString = {};
        qString[param] = is_numeric(req.query[param]) ? Number(req.query[param]) : req.query[param];
        matchQuery.push(qString);              
    }
    
    // Removed the toString() function call
    
    dbmodel.aggregate(
        {$match: {$and: strmatchQuery}}, // Removed the array [ ] 
        {$group: {
            _id: "$orderyear",
            totalorders: {$sum: 1}}
        }
    );