mongoose: update element in json array

送分小仙女□ 提交于 2021-02-10 09:08:29

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/62686488/mongoose-update-element-in-json-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!