This.userId inside publications.js


#1

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.


#2

If there is a logged in user you will have this.userId set to that current users _id inside the Meteor.publish(), If not then it will be set to null.


#3

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.


#4

Ok makes sense. Yes I was just trying to optimize my code. Everything works - just bothering me. Thank you for explaining.


#5

I think you have to use var curUser = Meteor.users.findOne(this.userId); inside every publication for which you need the specific user.


#6

If you just want to make your publications code more readable, you could define a global helper on the server

currentUser = function currentUser (context) {
  return Meteor.users.findOne(context.userId);
}

then in any publish method

currentUser(this)
...

#7

I use these globals for simplicity (coffee)

@curUserId= ->
	if Meteor.isClient then Meteor.userId()
	if Meteor.isServer then @userId 
@curUser = ->Users.findOne(curUserId)

#8

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