Home > Software design >  Filter method in MongoDB with optional fields
Filter method in MongoDB with optional fields

Time:01-27

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

CodePudding user response:

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