0

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.

2
  • Would you show a sample document in the collection? Commented Dec 4, 2017 at 15:21
  • 1
    If you need to reach that deep into a document to change something, you should probably re-think your schema Commented Dec 5, 2017 at 4:51

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.