Amplifying an array in a mongoose document
I have a json array with objects and I am doing the following loop to update (insert or update) data in MongoDB using mongoose:
var currentMiniApp;
function retResult(err) {
if (err) {
console.log(err);
}
}
for (var i = 0 ; i < miniappData.miniapps.length; i++) {
currentMiniApp = new MiniApp(miniappData.miniapps[i]);
MiniApp.findOneAndUpdate(
{id: currentMiniApp.id},
currentMiniApp,
{upsert: true},
retResult);
}
How can I do this in one command without using a loop?
I want the document to contain elements in a dataset
My data looks like this:
{
"miniapps" :
[
{
"id":"app1",
"icon" : "256fko6.png"
},
{
"id":"app2",
"icon" : "icon60x60.png"
}
]
}
+3
Dor cohen
source
to share
1 answer
Using a statement in your upsert update , This update operation adds multiple values ββto an array if the values ββare not already present, in which case it does nothing to that array: $addToSet
$each
$addToSet
var miniAppids = [];
for (var i = 0 ; i < miniappData.miniapps.length; i++) {
currentMiniApp = new MiniApp(miniappData.miniapps[i]);
miniAppids.push(currentMiniApp.id);
};
MiniApp.update(
{ "id": { "$in": miniAppids } },
{ "$addToSet": { "miniapps": { "$each": miniappData.miniapps } } },
{ "upsert": true },
retResult
)
+2
chridam
source
to share