Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose: update element in json array

I'm trying to update a user document that looks like this:

{
_id:"xyzdon'tcare",
username:"john",
examTrials:Array[
    {
        trialId:"x1",
        examId:"y",
        questions:Array[
            {ques1 Object},
            {ques2 object}
        ]
    },
    {
        trialId:"x2",
        examId:"z",
        questions:Array[
            {ques1 Object},
            {ques2 object}
        ]
    }]
}

I tried the most straightforward way, findOne() then modify the document then save().The problem is, I faced race condition problems with the document versions when a new request arrived before the previous update finished.

Now I'm tring to use findOneAndUpdate() to update a question object inside the questions array in a specific trial and I can't seem to figure out how to do this.

The information I have:

  • trial Id
  • question obj
  • question Id

I think this is all i need. Any help?

------------ EDIT

app.post('/updatetrialsession',authenticateJWT ,(req,res)=>{
        User.findOneAndUpdate({
        username: req.user.username
      }, {
           $set: {'examTrials.$[elem1].questions.$[elem2]' : req.body.question,
                'examTrials.$[elem1].currentQuestion':req.body.questionIdx+1 }
      }, {
           arrayFilters: [{'elem1.trialId': req.body.trialId }, {'elem2': req.body.questionIdx}]
      }).then(res=>{
          console.log("updated")
      })
})

currentQuestion updated, but the question object didn't.

like image 442
Mohammed Magdy Avatar asked Sep 05 '25 13:09

Mohammed Magdy


1 Answers

You can use mongoose arrayFilter to update your a field in an array.

For example if you have userId to query your user, trialId to query your exam trial, questionId to query your question, and newQuestionObject as your update to the question this code will do the work for you:

User.findOneAndUpdate({
  _id: userId
}, {
     $set: {'examTrials.$[elem1].questions.$[elem2]' : newQuestionObject}
}, {
     arrayFilters: [{'elem1.trialId': trialId}, {'elem2': questionId}]
});

Or if you want to update specific field of question object you can simply do that like this:

User.findOneAndUpdate({
  _id: userId
}, {
     $set: {'examTrials.$[elem1].questions.$[elem2].status' : 'newStatus'}
}, {
     arrayFilters: [{'elem1.trialId': trialId}, {'elem2': questionId}]
});
like image 192
Mahan Avatar answered Sep 11 '25 01:09

Mahan