Let's say I am conducting a search in the database:
router.post('/searchLoads', ensureAuthenticated, async (req, res) => {
var{ agentCode, loadNumber, pickupNumber, pickupDate } = req.body});
The user does not have to complete all fields. How can I construct a query using if statements? I attempted something like this:
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 += "})";
After creating the query, I'm unsure how to execute the code. Is there a simpler way to accomplish this?