Fred J.
Fred J.

Reputation: 6019

Meteor secure subscribe & publish

This Meteor code needs to publish one document which has field plateNum match value that is entered by the user.
Why is it not returning any thing? How to fix it?

//server.publications.js

Meteor.publish('myCol', function (plate) {
  if (this.userId && plate) {
    return myCol.find({plateNum: plate}, {fields: {a: 1, b: 1, c: 1, engineSize: 1 }});
  }
});

The values of the fields 'a', 'b', 'c' may not be ready at the time of the user request but will be calculated by a backend worker and update the myCol

//client.main.js

Meteor.subscribe('myCol', dict.get('plateNum'));  //<== stored info from user

Template.footer.events({
  'click #info': () => {
    searching = '<span class="note">Searching...</span>';
    let plate = document.getElementById('plateNum').value;
    plate = plate.replace(/\W/g, '').toLowerCase().trim();  //
    dict.set('plateNum', plate);  //<=== store user info here

    let doc = myCol.findOne({plateNum: plate});
    if (!doc || !doc.a) Meteor.call('aaa', plate);
    if (doc && !doc.b) Meteor.call('bbb', {plateNum: plate}, () => {});
    if (doc && doc.c && !doc.c) Meteor.call('ccc', {plateNum: plate}, () => {});
  }
});

Upvotes: 0

Views: 46

Answers (1)

kkkkkkk
kkkkkkk

Reputation: 7738

I guess it is because at the time your client code subscribes to myCol the this.userId is null therefore nothing is returned by server.

To fix this you need to make sure the user has been authenticated prior to subscribe

Update

This is the code you could use to fix it:

Template.footer.onCreated(function() {
  // use this.autorun over Tracker.autorun
  // so that the code below will be clear on onDestroy event
  this.autorun(function() {
    if(Meteor.userId()) {
      Meteor.subscribe('myCol', dict.get('plateNum'));
    }
  });
});

Upvotes: 0

Related Questions