How to create dynamic query in mongoose for update. i want to update multiple data(Not all) with the help of Id

Viewed 61

If I'm doing this, the field which I don't want to update is showing undefined. Any solution? (Like generating dynamic query or something)

exports.updateStudentById = async (req, res) => {
  try {
    const updateAllField = {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      field_of_study: req.body.field_of_study,
      age: req.body.age,
    };
    const data = await student_master.updateOne(
      { _id: req.body._id },
      { $set: updateAllField }
    );
    res.json({ message: "Student Data Updated", data: data });
  } catch (error) {
    throw new Error(error);
  }
};
1 Answers

You can go for a dynamic query creation .Example

const requestBody = {

  first_name: "John",
  last_name: "Cena",
  field_of_study: ""
}


const query={};

if(requestBody.first_name){
query["first_name"]=requestBody.first_name

}


 if(requestBody.last_name){
    query["last_name"]=requestBody.last_name
    
    }

Check for the fields that are present in req.body and create a dynamic query and when updating using mongoose use this

const data = await student_master.updateOne(
      { _id: req.body._id },
      { $set: query }
    );

In this way only those fields would be updated which are present in your req.body

Related