Updating an array item using NodeJS, MongoDB & Monk

ぃ、小莉子 提交于 2019-12-06 03:21:01

问题


I have a data set like this:

{ 
  name : 'Doc Name',
  photos: [
      {
        name: 'photo1',
        url: 'http://.....'
      },
      {
        name: 'photo2',
        url: 'http://......'
      }
   ],
   etc ...

Using Monk https://github.com/LearnBoost/monk how do I update photo2? I can use an index as I am iterating over the fields at the moment.

My current attempt below gives me an error, and I can't use a variable for the JSON selector (as in the index).

collection.update({_id: data._id}, {photos[i].data: filename}, function(err, updatedata) {

            });

回答1:


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" } }
)



回答2:


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);
    }
})


来源:https://stackoverflow.com/questions/21518416/updating-an-array-item-using-nodejs-mongodb-monk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!