Updating an array element using NodeJS, MongoDB & Monk

I have a dataset as follows:

{ 
  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 the index as I am sorting through the fields at the moment.

My current attempt gives me an error, and I cannot use the variable for the JSON selector (as in the index).

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

            });
+4
source share
2 answers

Updating elements 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" } }
)
+6
source

, , , . - , :

MongoDB Node.js, , . , - -:

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

Source: https://habr.com/ru/post/1524983/


All Articles