Youssef Mohamed Youssef Mohamed - 11 days ago 5
Javascript Question

How can I search in mongoose according to my query parameters?

I have a form that user can choose to search for transaction by specifying the buyer name or item name or both .. so I can have any of these queries :


localhost:8000/allPayments/?i=pasta

localhost:8000/allPayments/?b=Youssef

localhost:8000/allPayments/?b=Youssef&i=pasta


In the following code mongoose will always look for both of them

router.get('/allPayments', function (req, res, next) {
Transaction.find({'buyerName':req.query.b , 'itemName':req.query.i})
.then(function (docsPay) {
res.render('allPayments', {
payments: docsPay
});
});


How can I tell mongoose to only look for what is passed in the query without writing the above code 3 different times ?
For example : only do find({'buyerName':req.query.b}) if the query is the 2nd one

Answer

You can create query object first depending on conditions & then use that query object. Like :

var query = {};
var isParamPresent = false;

if( req.query.b != undefined && req.query.i != undefined ){
 query['buyerName'] : req.query.b;
 query['itemName'] : req.query.i;
 isParamPresent = true;

} 
else if ( req.query.b != undefined && req.query.i == undefined ){
 query['buyerName'] : req.query.b;
 isParamPresent = true;    
}
else if (req.query.b == undefined && req.query.i != undefined){
 query['itemName'] : req.query.i;
 isParamPresent = true;
}
else{
 isParamPresent = false;
 // both are undefined, your logic
}

if( isParamPresent ){

Transaction.find(query).then(function (docsPay) {
                                res.render('allPayments', {
                                    payments: docsPay });
//Further logic
}