Subscribe('notes') not grabbing correct records after signing in with different user

Basically, when I sign in I can see the right records. If I log out and log in with a different user I still see the old records. I need to refresh the browser before I see the right data.

How can I refresh the subscription so it grabs the right records seamlessly?

// lib/collections
Notes = new Mongo.Collection('notes');

// server
Meteor.publish('notes', function(userId) {
  return Notes.find({userId: userId});
});

// client
Accounts.onLogin(function() {
  Meteor.subscribe('notes', Meteor.userId());
});

// template
Template.noteList.helpers({
  notes: function() {
    return Notes.find();
  }
});

Why do I need to hard browser refresh to the see the right Notes collection? Appreciate the help in understanding Meteor a bit better.

first - never expect userID as argument for publish - you can get it server side safe way

and for subscription to change, you need to resubscribe.

So handle unsubscribing and resubscribing by hand, or let Tracker.autorun to do it for you.

@sergiotapia, although @shock is right, I think he missed an important point.

What you are doing wrong is that you never stop the previous subscription. When you call Meteor.subscribe, it adds a new subscription to the older one. As @shock said, you should either:

  • call handle.stop() on the previous subscription before calling subscribe again, or
  • call subscribe from an autorun

But, those solutions are not necessary, because Meteor has an automatic publish mechanism when user logs in/out. See [here][1] (second line). The optimal code is probably something like this, and nothing more:

// lib/collections
Notes = new Mongo.Collection('notes');

// server
Meteor.publish('notes') {
  return Notes.find({ userId: this.userId });
});

// Client
Meteor.startup(function () {
  Meteor.subscribe('notes');
});

// Template
Template.noteList.helpers({
  notes: function() {
    return Notes.find();
  }
});

UPDATED with @Sanjo remark below.
[1]: http://docs.meteor.com/#/full/publish_userId

1 Like

Thanks guys, I appreciate the help. @Steve in your // server block, what is this refering to? Should that be Meteor.user()._id?

Just have a look at the docs: http://docs.meteor.com/#/full/publish_userId

this is the publish context (just another name). The properties of this context are documented here.

I think in steves code the subscription is missing:

Meteor.startup(function () {
  Meteor.subscribe('notes');
});

Good catch @Sanjo. I have updated my post accordingly.

Awesome stuff! Learning new things every day here, appreciate it!