简体   繁体   中英

Create query based on inputs from user

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM