Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose dynamic query

Query parsed from URL, example :

?year=2014&cat=sonny

Or it can be

?year=2014&id=223&something=high&cat=sonny

I could do

Model.find({year: 2014}).where('cat').equals('sonny')

But what if there a second example? How can I make it dynamic?

like image 251
RaShe Avatar asked Nov 08 '14 18:11

RaShe


2 Answers

You can set the query to a variable and add multiple conditions:

var query = Model.find();

query.where('year').equals('2014');
query.where('cat').equals('sonny');
query.where('id').equals('223');
query.where('something').equals('high');
query.exec(callback);

For dynamic, just pass the query to a for loop and iterate through an array of your filter objects:

var query = Model.find();

var filters = [
    {fieldName: "year", value: "2014"},
    {fieldName: "cat", value: "sonny"}
    ...
];

for (var i = 0; i < filters.length; i++) {
    query.where(filters[i].fieldName).equals(filters[i].value)
}

query.exec(callback);
like image 143
chrisbajorin Avatar answered Sep 20 '22 00:09

chrisbajorin


Building on the cdbajorin's answer - I suspect many coders are trying to take input from a form and dynamically build a Mongoose filter from the end users input. (or at least that was my scenario).

If you 'name' the html input fields the same as your Mongoose Schema name

<input type='text' name='person.address'>

Then in your code you can use the req.body object

var query = Model.find();

for (var fieldName in req.body)
{
    if(req.body.hasOwnProperty(fieldName))  //no inherited properties
    {
        if(req.body[fieldName])  //get rid of empty fields
        {
            query.where(fieldName).equals(req.body[fieldName]);
        }
    }
}

query.exec(function(err,data){console.log('QUERY EXECUTE : ' + err, data, data.length);});
like image 37
DVon Avatar answered Sep 20 '22 00:09

DVon