Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter method in MongoDB with optional fields

I want to write a method in node js with mongodb that filters users by

  1. both batch and course
    2)only batch if course not enterted
    3)only course if batch not enterted
//filter students by either course or batch
export const getUsersByCourseOrBatch = async (req, res) => {
  try {
    const { course, batch } = req.body
    if(course, batch)
    {
      const users = await UserModel.find({ course: course, batch: batch })
    }
    else if(course)
    {
      const users = await UserModel.find({ course: course })
    }
    else
    {
      const users = await UserModel.find({ batch: batch })
    }
    res.status(200).json({
      message: `Users from course ${course} and batch ${batch}`,
      users,
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can build a custom filter object:

export const getUsersByCourseOrBatch = async (req, res) => {
  try {
    const { course, batch } = req.body;
    const filter = {};
    if (course) filter.course = course;
    if (batch) filter.batch = batch;
    const users = await UserModel.find(filter);
    res.status(200).json({
      message: `Users from course ${course} and batch ${batch}`,
      users,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading