Emil C.
Emil C.

Reputation: 101

best way to execute dynamic mongoDB queries in Nodejs

i have a variable that can either be an array of string or be an empty array.

const userHospitalQuery = [ req.query.hospital || [] ].flat();

when i filter with is as an array of strings, it works fine. Im running into a problem when i try to run my mongo search with the variable not having any values or empty (no Query pass in the url), how do I make mongo skip or ignore it as part of the filters? so only my other 2 filters are applied to the search. i know i cant use if statements inside my query object so im not sure what to do

const userHospitalQuery = [req.query.hospital || []].flat();

const filter = {
  "staff.hospital": { $in: userHospitalQuery }, // How do i ignore/skip this if no query is passed in the URL
  organisation: { $eq: "Test" },
  isDeleted: { $eq: false },
};

const staff = await User.find(filter).sort({ dateAdded: -1 });

Upvotes: 1

Views: 175

Answers (1)

AKX
AKX

Reputation: 168913

Just modify the filter object with a regular if.

const userHospitalQuery = [req.query.hospital || []].flat();

const filter = {
  organisation: { $eq: "Test" },
  isDeleted: { $eq: false },
};

if (userHospitalQuery.length) {
  filter["staff.hospital"] = { $in: userHospitalQuery };
}

const staff = await User.find(filter).sort({ dateAdded: -1 });

Upvotes: 1

Related Questions