'MongoDB : update or push an object in array
I'm working on APIs with NodeJS Express and mongoose. I have an issue to perform a query to update an array of objects in a document.
This is my document:
I have to do many operations, so I used bulkWrite() method. However, it performs only one operation and I don't know why.
var resultDetails = req.body.resultDetails;
await ScenarioRun.bulkWrite([{
// Case if the first resultDetails exists, so update
updateOne: {
"filter": { _id: req.params.id, "resultDetails.groupName": { $eq: resultDetails[0].groupName }},
"update":
{
$set: {
"errorMessage": req.body.errorMessage,
"status": req.body.status,
"result": req.body.result,
"resultDetails.$.groupResult" : resultDetails[0].groupResult,
"resultDetails.$.errorMessage": resultDetails[0].errorMessage
},
$addToSet: {
"resultDetails.$.contentLinks":
{
$each: resultDetails[0].contentLinks,
},
"resultDetails.$.actionsResults":
{
$each: resultDetails[0].actionsResults,
},
},
}
},
// Case if the first resultDetails does not exist, so push
updateOne: {
"filter": { _id: req.params.id, "resultDetails.groupName": { $ne: resultDetails[0].groupName }},
"update": {
$push: {
"resultDetails": resultDetails[0]
}
}
},
// Always push next resultDetails
updateOne: {
"filter": { _id: req.params.id},
"update": {
$push: {
"resultDetails":
{
$each: resultDetails.slice(1, resultDetails.length)
}
}
}
}
}]);
When resultDetails is empty, it only does the last case and not the second.
If I retry with commented last case, it does the second case.
Am I missing something ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|



