Search code examples
javascriptnode.jsmeteormeteor-accounts

Meteor userId is present but user is undefined


While rendering my react component I'm getting Meteor.user() null. Then I tried accessing Meteor.userId() and got it correct as the logged in user's id. Also tried to access the user by Meteor.users.findOne() but didn't succeed.

My question is, why user object is being undefined though the userid is accessible?

I used following code snippet to test:

var uid = Meteor.userId();
console.log(uid);                                 // printed the _id correctly

var usr = Meteor.user();                
console.log(usr);                                 // undefined 

var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1);                                // undefined 

Solution

  • Meteor.userId() is available immediately on login. Meteor.user() requires the object be delivered via DDP to the client so it's not immediately available.

    By default the profile key is published. Since you've turned off autopublish you may want to publish your own specific set of keys from the user.

    I usually have:

    server:

    Meteor.publish('me',function(){
      if ( this.userId ) return Meteor.users.find(this.userId,{ fields: { key1: 1, key2: 1 ...}});
      this.ready();
    });
    

    client:

    Meteor.subscribe('me');
    

    You can also publish information about other users but there the list of keys to be shared is typically much smaller. For example you usually don't want to share the email addresses of other users with the logged-in user.