ylwester
ylwester

Reputation: 59

MongoDB find from queryparams

Im trying to create some sort of filter data on my project. Im sending request by query params to server and based on that I respond with data that user wants.

I have something like this: and it works if category if defined, or if isPaid is defined, but it doesn't work if they both are defined and i have no clue how to accomplish that

router.get('/', (req, res)=> {
    let category = req.query.category;
    let isPaid = req.query.paid;

    if(category !== undefined || isPaid !== undefined) {
        EventItem.find({$or : [{"categories.id": category}, {"isPaid": isPaid}]})
            .then(events => res.json(events))
            .catch(err => console.log(err));
    } else {
        EventItem.find()
            .then(events => res.json(events))
            .catch(err => console.log(err));
    }
})

I want to make a query where:

If isPaid is set, then it gives me events that are free/paid

If category is set, then it gives me events from that category

if isPaid & category is set, it gives me free/paid events from this category.

How can i do that? In a future i will have more sorting options, so writing by hand every if statement is not efficient, i would like to know how to combine those params THANKS

Upvotes: 0

Views: 31

Answers (1)

Someone Special
Someone Special

Reputation: 13588

You can build your query before you execute it.

   const { category, isPaid } = req.query

   let find = {};

   find = category ? { ...find, category } : find
   find = isPaid ? { ...find, isPaid } : find

   EventItem.find(find)

if both category and isPaid is not set then find = {} which means return everything. You may pre-build your query the same way using "$or" and array

Upvotes: 1

Related Questions