Reputation: 311
So lets say I am running a search through the database
router.post('/searchLoads', ensureAuthenticated, async (req, res) => {
var{ agentCode, loadNumber, pickupNumber, pickupDate } = req.body});
The user is not required to fill out all fields. How would I build a query based on if statements? I was trying something along the lines of
result = 'await Load.find({';
if (agentCode !== undefined){
result += "agentCode: agentCode, ";
}
if(loadNumber !== undefined){
result += "loadNumber: loadNumber, ";
}
if(pickupNumber !== undefined){
result += "pickupNumber: pickupNumber, ";
}
if(pickupDate !== undefined){
result += "pickupDate: pickupDate, ";
}
result += "})";
But I am not sure how to then run the code now that I've created the query. Is there an easier way to do this?
Upvotes: 0
Views: 200
Reputation: 1411
Instead of creating a string, you could create an object.
Assuming we are using ES6+ we can use agentCode
instead of agentCode: agentCode
while initializing fields.
var options = {
agentCode,
loadNumber,
pickupNumber,
pickupDate,
};
result = await Load.find(options);
The !== undefined
checks are not necessary, since undefined
fields will be dropped.
Upvotes: 1