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.