繁体   English   中英

如何使用Meteor获取当前用户的用户名

[英]How to get current user's username with Meteor

到目前为止,我一直在寻找各种各样的互联网和Meteor文档,但没有任何东西对我有用。

我正在创建一个帐户

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

而且我知道自{{#if currentUser}}正在运行以来它正在发挥作用。

但是,我试图获取当前登录用户的用户名,例如

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

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

但是当我使用Meteor.userId()时,两者都没有工作,我只是随机(我猜是加密的)数字和字母串,当我使用Meteor.userId().username它说它是未定义的。

所有的帮助都是受欢迎的,对不起我可能很糟糕的语法,这里已经很晚了!

Meteor.userId()Mongo.users集合返回用户的_id。 这就是为什么它看起来像一个毫无意义的字符串。

你想要Meteor.user() 文档是你最好的朋友:)

试试{{currentUser.username}}

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

我认为Accounts.createUser - > username只会设置Meteor.user()。profile.name。 如果你想拥有Meteor.user()。用户名,你应该使用Accounts.onCreateUser( https://docs.meteor.com/#/full/accounts_oncreateuser )并添加用户名字段,如:

Accounts.onCreateUser(function (options, user) {

    user.username = user.profile.name;

    return user;

});

这是因为Meteor.user()。用户名是这种情况下的自定义字段。

添加到客户端js

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

我是这样做的:

  1. 包括一个帐户包:meteor add accounts-password
  2. 从'流星/流星'导入{流星}
  3. console.log('Username:'+ Meteor.user()。username);

用户需要登录,否则Meteor.user()返回null。

编辑:还要记住,在将用户集合发送到客户端之前,Meteor.user()将不可用。

一体!

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

然后,您可以将值返回到变量,State或Session ..etc

Meteor.userId();

上面的代码返回一个字符串,该字符串是已记录用户Meteor.userId()的唯一ID,而不是整个用户对象。 所以你不能尝试任何财产。 要使当前用户名执行如下操作:1 - /在流星控制器中

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

2 - /在流星模板中

{{ currentUser.username }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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