Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current user's username with Meteor

So far I've been looking all over the interwebs and the Meteor docs but nothing has been working for me.

I am creating an account with

Accounts.createUser({
    username: username,
    email: email,
    password: password
});

And I know that is working since {{#if currentUser}} is working.

However, I am trying to get the current logged-in user's username with something such as

var username = Meteor.userId();
console.log(username);

var username = Meteor.userId().username;
console.log(username);

But neither is working, when I use Meteor.userId() I just get a random(I'm guessing encrypted) string of numbers and letters, and when I use Meteor.userId().username it says it's undefined.

All help is welcome and sorry for my possibly terrible grammar, It's very late here!

like image 285
David Chalifoux Avatar asked Nov 04 '14 05:11

David Chalifoux


3 Answers

Meteor.userId() returns the _id of the user from the Mongo.users collection. That's why it looks like a meaningless string.

You want Meteor.user(). The docs are your best friend :)

like image 186
Dan Dascalescu Avatar answered Sep 22 '22 12:09

Dan Dascalescu


Try with {{currentUser.username}}

like image 35
darkcode Avatar answered Sep 23 '22 12:09

darkcode


I am doing it like this:

  1. Include an accounts package: meteor add accounts-password
  2. import { Meteor } from 'meteor/meteor'
  3. console.log('Username: ' + Meteor.user().username);

User needs to be logged in, else Meteor.user() returns null.

Edit: Also keep in mind Meteor.user() will not be available until the users collection is sinced to the client.

like image 21
Angel Pateiro Avatar answered Sep 25 '22 12:09

Angel Pateiro