I am using the where method to pass the fieldname and the value to a Mongoose fineOne query.
Model.findOne().where(field1,value1).where(field2, value2).exec(function(err,callback) {
...
}
The above works find. However, my problem is that we have more fieldnames and values to be passed to the above statement. I don't know exactly the number of fieldname and the value to be used since it depends on the user's configuration. I like to use a for loop to dynamically build the where clause, but don't know how. Can someone help?
You can create a variable for the conditions:
var conditions = {};
for (i = 1; i < 3; i++) {
conditions['field' + i] = 'value' + i;
}
The conditions object will look like this:
console.log(conditions);
Object {field1: "value1", field2: "value2"}
This for loop is of course just an example, you can use kind of loop to build the object. Then you can execute the findOne() query this way:
Model.findOne(conditions, function(err, item) {
// ...
});
Assuming a values object that contains the values of the fields you want to save, and a fields array that contains the name of the fields to save, you could do it like this:
var values = {p_last_name: 'Smith', p_first_name: 'John', ... };
var fields ['p_last_name', 'p_first_name'];
var query = Model.findOne();
for (var i=0; i<fields.length; ++i) {
var field = fields[i];
query.where(field, values[field]);
}
query.exec(callback);