I’m trying to declare a variable on the top of publication.js file because I’m going to use it over and over again. So because I can’t use Meteor.user() inside any publication function function, I’m trying to declare the following variable:
var curUser = Meteor.users.findOne(this.userId);
This doesn’t produce an error, but it also don’t find the user that’s currently logged in. I need to use a profile field throughout my publications (for certain users based on their roles). I’m not sure how else to do this. NOTE: This works if I repeatedly declare the variable inside each publication function. This produces an error:
var curUser = Meteor.users.findOne(Meteor.userId());
It says that I can’t use Meteor.userId() inside a publication function (even though I’m not using it in that context). I’m really stumped on this issue. I can get around it by repeatedly declaring the same variable over and over again, but I’d prefer not do that.
If you mean that you are trying this outside of the Meteor.publish like this…
var curUser = Meteor.users.findOne(this.userId);
Meteor.publish("somePublication", function() {
return collection.find();
});
That is not possible… On the client Meteor.user() and Meteor.userId() are available from any code because the browser holds the context of the current user… On the server the connection to the server holds the context of the current user so getting the ID for the current user can’t happen outside of code that is aware of the users connection. Hopefully this makes sense.
If this is the case then I’m guessing you are trying to make an optimization by only getting the userId once and storing it, but If you call use this.userId from inside the publish or meteor method then its already stored for you so it doesn’t need further optimization.
Package universe:collection provides UniUsers.getLoggedIn(), which works even in publication.
It useful in situations when you aren’t access to publish context but you are in scope of publish function