Theres is a part of my application where i can specify some filters to retrieve certain data. But not all the filters are necessary so i can left some of them empty and the query just wouldn't use them. How can i achieve this in mongoDB. Thanks in advance.
client-side:
$('#filter').click(function(e){
e.preventDefault();
var filters = JSON.stringify({ Marca : $('#Marca').val(), Modelo : $('#Modelo').val(), Fecha : $('#Fecha').val()});
$.ajax({
type: 'POST',
data: filters,
url: '/filterFees',
contentType: 'application/json'
}).done(function( response ) {
if(response.msg === ''){
filterFees(response.data);
}
else {
alert('Error: ' + response.msg);
}
})
})
node.js(using monk):
app.post('/filterFees', function(req, res){
var db = req.db;
var collection = db.get('Fees');
collection.find({'Marca' : req.body.Marca, 'Modelo' : req.body.Modelo, 'Fecha' : req.body.Fecha, },{},function(err,docs){
res.send((err === null) ? { msg: '', data : docs } : { msg:'error: ' + err });
});
})
Check if there the value exists in the filters
var filter = {}, filters;
if $('#Marca').val()
filter.Marca = $('#Marca').val();
if $('#Modelo').val()
filter.Modelo = $('#Modelo').val();
if $('#Fecha').val()
filter.Fecha = $('#Fecha').val()
filters = JSON.stringify(filter);
and find data where filters
collection.find(req.body,{},function(err,docs){
res.send((err === null) ? { msg: '', data : docs } : { msg:'error: ' + err });
});
PS. not sure why you stringify the parameters instead of sending object