简体   繁体   中英

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!

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 :)

试试{{currentUser.username}}

你必须在.js文件和html文件中使用username: Meteor.user()使用{{username.profile.name}}

I think that Accounts.createUser -> username will set up only Meteor.user().profile.name. And if you want to have Meteor.user().username you should probably use also Accounts.onCreateUser ( https://docs.meteor.com/#/full/accounts_oncreateuser ) and add username field like:

Accounts.onCreateUser(function (options, user) {

    user.username = user.profile.name;

    return user;

});

It is that way because Meteor.user().username is a custom field in this case.

add to clients js

Accounts.ui.config({
  passwordSignupFields: 'USERNAME_AND_EMAIL'
});

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.

All in One!

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

Then you can either returned value to variable, State or Session ..etc

Meteor.userId();

This code above return a string that is the unique ID of the logged user Meteor.userId() not the whole user object. So you can not attempt to any property . To have the current username do as following: 1 - / In meteor controller

var uniqueID = Meteor.userId(); 
var username = Meteor.users.findOne({_id: uniqueID}).usename;

2 - / In meteor template

{{ currentUser.username }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM