How to replace element of child array in Node.js&MongoDB

Viewed 60

Please help me to update an element of the child array in node. I tried this, but it replaced all object.

var assignId = req.body.data.assign_id;
var answer = {
    mark: mark,
    isCorrect: isCorrect
}

AssignModel.findOneAndUpdate(
    { _id: assignId },
    {
      $set: {
        "answers": answer
      }
    }, 
    function (err, doc, result) {
      if(err) { 
        return next(err)
      } 

      res.json({
        success: true,
        result: result
      })
});

This is the origin data type in MongoDB.

https://prnt.sc/wak8xy

I want to change the mark of the second object.

https://prnt.sc/wak9i2

But after run the above code, it changed like this.

https://prnt.sc/wak8cd

If you know how to implement that, please help me. Thanks.

1 Answers

Quick fixes:

  • search by answer field, i have searched by answers._id, you can put your correcte field in query part,
  • if you want to update specific fields then use dot notation along with main field like answers.$.mark, and $ indicates to update in searched element in query part, I have added set variables with update fields, and passed to direct $set in update part,
var assignId = req.body.data.assign_id;
var set = {
    "answers.$.mark": mark,
    "answers.$.isCorrect": isCorrect
};
AssignModel.findOneAndUpdate(
    { 
        _id: assignId,
        "answers._id": answerId
    },
    { $set: set }, 
    function (err, doc, result) {
        if(err) { return next(err) } 
        res.json({
            success: true,
            result: result
        })
    }
);
Related