meteormeteor-publications

Meteor publications/subscriptions not working as expected


I have two publications.

The first pub implements a search. This search in particular.

 /* publications.js */
Meteor.publish('patients.appointments.search', function (search) {
    check(search, Match.OneOf(String, null, undefined));

    var query = {},
    projection = { 
         limit: 10,
         sort: { 'profile.surname': 1 } };

    if (search) {
        var regex = new RegExp( search, 'i' );

        query = {
            $or: [
                {'profile.first_name': regex},
                {'profile.middle_name': regex},
                {'profile.surname': regex}
          ]
     };

    projection.limit = 20;
}
   return Patients.find(query, projection);
});

The second one basically returns some fields

/* publications.js */
 Meteor.publish('patients.appointments', function () {
   return Patients.find({}, {fields:  {'profile.first_name': 1,
                'profile.middle_name': 1,
                'profile.surname': 1});
});

I've subscribed to each publication like so:

/* appointments.js */
Template.appointmentNewPatientSearch.onCreated(function () {
    var template = Template.instance();

    template.searchQuery = new ReactiveVar();
    template.searching = new ReactiveVar(false);

    template.autorun(function () {
       template.subscribe('patients.appointments.search', template.searchQuery.get(), function () {
          setTimeout(function () {
              template.searching.set(false);
          }, 300);
       });
    });
});


Template.appointmentNewPatientName.onCreated(function () {
    this.subscribe('patients.appointments');
});

So here's my problem: When I use the second subscription (to appointments.patients), the first one doesn't work. When I comment the second subscription, the first one works again. I'm not sure what I'm doing wrong here.


Solution

  • The issue here is you have two sets of publications for the same Collection. So when you refer to the collection in client there is now way to specify which one of the publication it has to refer too.

    What you can do is, publish all data collectively i.e. all fields you are going to need and then use code on client to perform queries on them.

    Alternatively, the better approach will be to have two templates. A descriptive code:

    <template name="template1">
       //Code here
          {{> template2}}   //include template 2 here
    </template>
    
    <template name="template2">
         //Code for template 2
    </template>
    

    Now, subscribe for one publication to template one and do the stuff there. Subscribe to second publication to template 2. In the main template (template1) include template2 in it using the handlebar syntax {{> template2}}