Is there a way to use a variable for the field name in a find() in mongoose?
Just put the variable in []
function foo (field, value){
Model.find({[field]: value});
}
foo('idfoo', 'xx');
foo('idbar', 5);
You could use the built in where
function, making the call to the function you've shown unnecessary:
Model.find().where(fieldName, value).exec(function(err, results) { });
And you could do more than one via chaining:
Model.find().where(field1, val1).where(field2, val2).exec(...)
It also can be rich, supporting nested properties and other operators:
Model.find().where('orders.total').gt(1500).exec(...)
function foo(field, value) {
var query = {};
query[field] = value;
Model.find(query)...
}