Search code examples
javascriptmeteoriron-router

Meteor subscription in iron:router controller isn't working


I am using iron:router in my app and I have a controller that subscribes to one document in a collection by using a parameter in the path. I can access all of the documents in my collection on the server, so I know that there is stuff in there, but when I try to access the data that I subscribe to in the waitOn method of the controller, the data is undefined. Here is the relevant code for this problem.

Router code:

this.route('unit', { path: 'unit/:unitId', template: 'unit', controller: 'UnitController' });

UnitController = BaseController.extend({
  waitOn: function () {
    return Meteor.subscribe('getUnit', this.params.unitId);
  },
  data: function () {
    var id = this.params.unitId;
    
    templateData = {
      unit: Collections.units.model(Collections.units.getUnit(id))
    };
    return templateData;
  }
});

Publication:

Meteor.publish('getUnit', function(id) {
  return Collections.units.data.find({ unitId: id });
});

Here I have created an object for various things to do with my collection(I only included the important parts here):

Collections.units = {
	data: new Mongo.Collection("units"),
	getUnit: function (id) {
		return this.data.findOne({ unitId: id });
	},
	model: function(unitEntity) {
       return {
  	      unitId: unitEntity.unitId,
  	      createdAt: unitId.createdAt,
  	      packets: unitEntity.packets,
  	      getLastPacket: function (id) {
  		     return _.last(this.packets);
  	      }
       };
    }
};

I have been trying to debug this for quite a while and I can do all the things to the collection I want to on the server and in the publish method, but when it gets to the controller, I can't access any of the info. In the data method this.params.unitId returns exactly what I want so that isn't the issue. Where the exception gets thrown is when I try to read properties of unitEntity when I'm making the model but that is just because it is undefined.

Have any ideas what I am doing wrong? Thanks in advance for any responses.


Solution

  • The main problem that I was trying to solve's solution was to wrap the code inside the data method inside of if (this.ready()){ ... } and add an action hook with if (this.data()) { this.render(); }. After I got the subscription to work, I found that Christian was right in the comments with saying that my controller setup might mess things up. It was causing other strange exceptions which I fixed by just moving the hooks to each route instead of using the controller. As for my Collections setup, it may be unconventional, but all of that is working fine (as of right now). I may want to set them up the standard way at a later point, but as of right now its pretty handy for me to do things with the collections with the methods already written in the object.