I'm working with mongodb, with a ajax form, it works fine... i want to discard some elements in the query. this is the code:
var preVariable=
{
precio_alquiler: {$lte:query.price_input_by_user},
tipo_usuario: query.type_of_user,
};
db.collection('data').find(preVariable,{_id:0},{safe:true}, function(err, result)
Explanation:
precio_alquiler is the price of the element
tipo_usuario is a select in the form that contains
select(name='type_of_user')
option(value="Commerce") Comercio
option(value="User") Usuario
option(value="Mayorist") Mayor
So the question is... if the user want to consult the price of an element and ignore the type of the user, how to create the query variable??? Here's an example that can explain the question
var preVariable=
{
precio_alquiler: {$lte:query.price_input_by_user},
tipo_usuario: query.type_of_user || "dont create the object tipo_usuario",
};
You could create different object:
var preVariable = query.type_of_user ? {
precio_alquiler: {
$lte: query.price_input_by_user
},
tipo_usuario: query.type_of_user
} : {
precio_alquiler: {
$lte: query.price_input_by_user
}
};
A common practice is to initialize the object with known properties at first, and conditionally add those that are depending on input:
var preVariable = {
precio_alquiler: { $lte: query.price_input_by_user }
};
if(query.type_of_user) {
preVariable.tipo_usuario = query.type_of_user;
}
If you have a lot of these fields, then this may be better than using conditionals:
var preVariable = {
precio_alquiler: {$lte:query.price_input_by_user},
tipo_usuario: query.type_of_user,
//... more
};
// Remove the undefined fields
for (var prop in preVariable) {
if (preVariable[prop] === undefined) delete preVariable[prop];
}