How do I make a conditional query to a mongodb database?

Issue

I’m trying to make a filtering component for my website and I want to be able to get that data which they specified through the filter from the MongoDB database. I’m using MERN stack and want to conditionally send a query to the database to retrieve based on whether or not it’s empty or not. If it’s empty, it means the user wants anything in that specific category and not one specific thing so I don’t want to send an empty query to the DB which is just going to look for an empty string/array and realize that nothing in the DB has an empty string/array and won’t return anything.

That’s why I want to conditionally render my query parameter because that’s the only workaround I can think of for my earlier question which does not have a solution for:
How can I send an object as a query and use the $all operator in MERN stack?

Here is the code and where I want the the conditional render to happen:

    var t = ["People"]
    const test = await Project.find( {$all: {
        theme: t // have something that condditionally sends this, if t is empty then don't send it
    }}
    ).sort({ createdAt: -1 })
    console.log(test)

Solution

You can conditionally construct the search-filter:

const filter = {};
if (t.length) { // or whatever condition you need
  filter.$all = {theme: t};
}

const test = await Project.find(filter) // rest of your code

Answered By – eol

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published