Meteor.userId().username is “undefined” when user is logged in

So, I have a logged in user (myself) in my app. I know I’m logged in, because my username is displayed in the page. However, in my Javascript, I am unable to get my username assigned to a variable.

My main.js file contains this:

var uniqueID = Meteor.userId();
var username = uniqueID.username;
console.log("uniqueID = "+uniqueID);
console.log("username = "+username);

The console log shows:

uniqueID = XGX8Qas2ZLCwNYxTH
username = undefined

I tried the following line in the js file based on a post with a similar issue:

var username2 = Meteor.users.findOne({ _id: Meteor.userId() }).username

This caused an outright error (Uncaught TypeError: Cannot read property ‘username’ of undefined)

Now, in the browser console, if I put in:

Meteor.users.findOne({ _id : “XGX8Qas2ZLCwNYxTH” })

I get the expected response: {_id: “XGX8Qas2ZLCwNYxTH”, username: “wlehman”}

So I am at a complete loss as to how to pull in the username. I actually had this working before, but now that I actually need it, of course it suddenly doesn’t work.

Meteor.userId() returns the _id of the current user.

Meteor.user() returns the user record of the current user.

1 Like

Thanks, changing that worked!