meteormeteor-publications

Meteor Publications/Subscriptions not working


I'm a bit of a noob and having a bit of trouble getting my publications to work. In my data, I have a number of patients and would like to show the data of a single patient. This is how I have structured my publication:

Meteor.publish('patients.single', function (patientId) {
  check(patientId, String);
  return Patients.find({_id: patientId});
});

and this is how I have subscribed:

Router.route('/patients/:_id', {
  layoutTemplate: 'ApplicationLayout',
  yieldRegions: {
    'single_patient': {to: 'content'}
  },
  subscriptions: function () {
    return Meteor.subscribe('patients.single', this.params._id);
  }
});

I have also tried to subscribe via the actual template to no avail:

Template.patient_details.onCreated(function () {
  this.subscribe('patients.single', Session.get("currentPatient"));
});

Publications seem easy in theory, but I just can't seem to get them right. What am I doing wrong here?


Solution

  • It takes time for the subscription to get the data from the server to the mini mongo, so you have to wait for the subscription to be ready, before using the data that It will get for you.

    If you are using Iron Router try using waitOn instead of subscribe, that will force the router to wait for the subscription to be ready and will render the loading template while its getting the subscription data.

    Router.route('/patients/:_id', {
      layoutTemplate: 'ApplicationLayout',
      yieldRegions: {
        'single_patient': {to: 'content'}
      },
      waitOn: function () {
        return Meteor.subscribe('patients.single', this.params._id);
      }
      data: function () {
        return Patients.findOne({_id: this.params._id});
      },
    });
    

    You can also use the data property, that way you will have the data available in your template instance.data.