RaShe
RaShe

Reputation: 1880

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?

Upvotes: 5

Views: 13629

Answers (2)

DVon
DVon

Reputation: 31

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);});

Upvotes: 3

chrisbajorin
chrisbajorin

Reputation: 6153

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);

Upvotes: 7

Related Questions