Search code examples
arraysmongodbsetpublishmeteor

How can I set nested array values in meteor publish function?


I have two collection "contents" and "units". In the content collection is a field "unitID" which refers to the unit-collection. In the meteor publish function I want to add the unit type name of all new created contents:

Meteor.publish("contents", function () {
  var self = this;

  var handle = Contents.find().observe({
    changed: function(contentdoc, contentid) {
        var UnitName = Units.findOne({_id: contentdoc.unittypeid }, {fields: {type: 1}});

        self.set("contents", contentid, {'content.0.typename': UnitName});
        self.flush();
    }
  });
}

This works but it creates a new attribut "content.0.UnitName" instead of inserting the attribute "UnitName" in the first element of the content array:

[
    {
       _id:"50bba3ca8f3d1db27f000021",
       'content.0.UnitName':
       {
           _id:"509ff643f3a6690c9ca5ee59",
           type:"Drawer small"
       },
       content:
       [
           {
               unitID:"509ff643f3a6690c9ca5ee59",
               name: 'Content1'
           }
       ]
    }
]

What I want is the following:

[
    {
       _id:"50bba3ca8f3d1db27f000021",          
       content:
       [
           {
               unitID:"509ff643f3a6690c9ca5ee59",
               name: 'Content1',
               UnitName:
               {
                    _id:"509ff643f3a6690c9ca5ee59",
                    type:"Drawer small"
                }
           }
       ]
    }
]

What am I doing wrong?


Solution

  • this.set within Meteor.publish only works on the top-level properties of an object, meaning it doesn't support Mongo-style dotted attributes. You'll have to call set with the entire new value of the contents array.