Updating an array item using NodeJS, MongoDB & Monk

梦想与她 提交于 2019-12-04 10:11:38

Updating items at a position in an array can be done using the positional $ operator

collection.update( 
    { _id: data.id, "photos.name": "photo2" }, 
    { $set: { "photos.$.data": "yourdata" } }
)

So I found a solution to my problem but there may be some better options and I will leave it unanswered. But for anyone else with the same issue this is what I did:

I extracted the MongoDB document as an object in Node.js, manipulated the document, and then replaced the entire array in a single update statement. For example here is some pseudo code:

collection.find({id: 1}, function(err, doc){
    for(i=0; i< doc.array.length; i++) {
          //do what you gotta do
          doc.array[i].property = 'new value';
    }
    collection.update({id: 1}, {$set : {"doc.array": doc.array}}, function(err,doc){
          console.log(err);
    }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!