Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.userId returns undefined inside Meteor.publish

In one of my Meteor.publish() functions, this.userId has the value of undefined. I can't call Meteor.userId() because it's not available inside a publish function. How are you supposed to get userId now?

like image 942
Alex Forsyth Avatar asked Jan 16 '15 19:01

Alex Forsyth


1 Answers

There are four possibilities:

  1. There is no user logged in.

  2. You're calling the method from the server, and there will thus be no user associated with the call (unless you're calling it from another function which will have a user bound to its environment, like another method or a subscribe function).

  3. You don't even have the accounts-base package (or any of the add-ons) installed. I'm only including this for completeness.

  4. You are using an arrow function in ES6. Meteor.publish('invoices', function() { return invoices.find({by: this.userId}); }); will work just fine, whilst Meteor.publish('invoices', () => { return invoices.find({by: this.userId}); }); will return an empty cursor, because this will have no userId property. This happens because an arrow function does not bind its own this, arguments, super, or new.target.

If it's definitely not (2), what happens when you log Meteor.userId() immediately before you make the method call on the client?

like image 144
richsilv Avatar answered Sep 27 '22 17:09

richsilv