mongodbmeteormeteor-collections

Meteor: Update object nested two arrays deep


I have a collection with a key called fields, which is an array of JSON objects. Those objects can have options which is another array of JSON objects. I’m trying to update one of the options by optionId. I tried this but it doesn't work.

Projects.update({
  'fields.options._id': optionId
}, {
  $set: {
    `fields.$.options.$.title`: title
  }
}

This does find the correct Project document, but doesn't update it.


Solution

  • You can use the $ operator for single level arrays only. Use of array1.$.array2.$.key is not supported.

    However, if you are aware of the exact index of the element to be updated within the array, you can update like so:

    Projects.update({
      'fields.options._id': optionId
    }, {
      $set: {
        `fields.0.options.1.title`: title
      }
    }
    

    This is one way to update:

    Projects.find({"fields.options._id":optionId}).forEach(function(record) {  
        var match = false;
        // iterate fields array
        for(var i=0; i< record.fields.length; i++){
          // iterate options array 
          for(var j=0; j<record.fields[i].options.length; j++){
    
            if(record.fields[i].options[j]._id == optionsID){
               record.fields[i].options[j].title = title;
               match = true;
               // break;
           }
    
          }
        }
    
    
        if (match === true) Projects.update( { 'fields.options._id': optionId }, record );
    
    });
    

    Source