I have array of objects with following structure:
const myArr = [{
'name':'question1',
'grade':6
},
{
'name':'question2',
'grade':7
}]
Question collection:
{
_id:623749f845844e7d273d801c,
questions:[
{
'name':'question1',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801m
},
{
'name':'question2',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801a
},
{
'name':'question3',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801f
}
]
}
I just want to update all objects in array questions in collection which i have provided in myArr array. So the desired result should be:
{
_id:623749f845844e7d273d801c,
questions:[
{
'name':'question1',
'grade':6,
'someInfo':'blabla',
_id:623749f845844e7d273d801m
},
{
'name':'question2',
'grade':7,
'someInfo':'blabla',
_id:623749f845844e7d273d801a
},
{
'name':'question3',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801f
}
]
}
What i've found so far:
I managed to update grade when i specify the question name with positional operator:
await Prijave.updateOne(
{
_id: mongoose.Types.ObjectId(q_id),
'questions.name': 'question1',
},
{
$set: {
'questions.$.grade': '10',
},
}
)
But how to do this for every element in myArr ? I could make forEach loop which iterates through myArrand call updateOne for every element but i dont think it should be done that way because it will make multiple connection to database instead of one.