1

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 });

1 Answer 1

1

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 });

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

Comments

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.