1

I was reading the docs but could not find a way to do this "double" updates.

First the collection:

meteor:PRIMARY> db.radioOptions.find({}).pretty();
{
 "_id" : "n8DsDzsPL8JTRFEQ8",
 "name" : "optionType",
 "value" : [
  {
   "name" : "1stOption",
   "caption" : "1st Option",
   "checked" : true <-------- run code added this property
  },
  {
   "name" : "2ndOption",
   "caption" : "2nd Option",
   "checked" : true <-------- run code added this property
  }
 ]
}

And here is the code that run which added the marked property. credit

  RadioOptions.update(
    {name: obj.name, 'value.name': obj.value},
    {$set: {'value.$.checked': true}}
  );

But I also want to either set the other embedded documents to false or remove their property checked:true so that there will only be one embedded document with its checked field is set to either true or checked.

My failed attempt: bruteforce

  RadioOptions.update(
    {name: obj.name, 'value.name': obj.value},
    {$set: {'value.$.checked': true}, $set: {$ne: {'value.$.checked': false}}}
  );

How can this get done? Can I do this in one run of the update method ?

edit After reading the link suggested as a duplicate.

My updated code below is failing in that the update lines are updating the first doc with checked:false and the second with checked:true no mater what the condition evaluates to, which has been verified to evaluate correctly.

  var doc = RadioOptions.findOne({name: obj.name});
  if (typeof doc != 'undefined') {
    doc.value.forEach(function (embdoc) {
      // how to update so that to use $unet the "checked" property of all embedded documents in the value array?
      if (embdoc.name == obj.value) {
        RadioOptions.update(
          {name: obj.name, 'value.name': obj.value},
          {$set: {'value.$.checked': true}}
        );
      }
    })
  }
Fred J.
  • 5,759
  • 10
  • 57
  • 106
  • How important is it that this be done in a single `update` operation? It seems like you could first remove the property from all of the elements and then update only the matching one, __or__ you could find the document, update the values in memory, and then `$set` the entire array. – David Weldon Mar 11 '16 at 00:37
  • If there is no way to do it in one update operation, then I have no choice but to do settle for you first suggestion. – Fred J. Mar 11 '16 at 00:41
  • That wasn't the lesson to learn from the linked duplicate ( which your question still is a duplicate of ). Each `.update()` in the loop is meant to match something in the target array entry to identify it. Your code should just be setting "all" elements to `false` and then only the target element to true. The positional operator still only matches "one" item at a time. – Blakes Seven Mar 11 '16 at 05:32
  • I edited the code again but unable to $unset all the checked property. need help, still learning. – Fred J. Mar 11 '16 at 06:09

0 Answers0