Home > Mobile >  Mongoose: how to set a query that $in everything if there is no value selected?
Mongoose: how to set a query that $in everything if there is no value selected?

Time:12-26

I am trying to apply the filter to my aggregate search right now. Currently, I can't set the value $in: to include everything.

if (gameType.length === 0) {
    query = {
      gameCode: {
        $in: gameCode,
      },
   
    };
  } else {
    query = {
      gameType: {
        $in: gameType,
      },
      gameCode: {
        $in: gameCode,
      },
    };
  }

The above code is what I have. Users can select more than one gameType. Because, I don't know how to set $in to include everything, I have used the if statement to exclude gameType from the query when user has not selected any = returning all the gameType.

Is there any way that I can set a variable to search every gameType besides providing the array with all the values (I will probably do that if there is no way that I can do this)?

CodePudding user response:

If you have many different filter options, you can just build your query dynamically:

const query: FilterQuery<Game> = {};
if (gameType.length) {
  query.gameType = {$in: gameType};
}
if (gameCode.length) {
  query.gameCode = {$in: gameCode};
}
// ...

You can add more if statements if you have more conditions. Keep in mind that all conditions are ANDed, i.e. all must be true.

  • Related