0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This almost gets me there. But when I console log options it outputs { agentCode: 'JQL', loadNumber: '', pickupNumber: '', pickupDate: '', pickupTime: '', shipperFacility: '', shipperAddress: '', shipperCity: '', shipperState: '', shipperZip: '', shipperPhone: '', deliveryDate: '', deliveryTime: '', destinationFacility: '', destinationStreetAddress: '', destinationCity: '', destinationState: '', destinationZip: '', destinationPhone: '', completed: undefined } Which then searches the DB for empty strings
Then I would console.log(...) each of the fields you're putting into it. If I had to guess, console.log(pickupNumber) would give you ` '', pickupDate: ''` as output. This is likely a problem with your input/HTTP-request
Even with the inputs disabled on form onsubmit, it still passes an object that searches for field: undefined
NVM Just added this for(const [key, value] of Object.entries(options)) { if(options[key] == undefined){ delete options[key]; } } and it worked :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.