meteoruserId存在,但用户未定义

在渲染我的反应组件时,我得到了Meteor.user() null 。 然后,我试图访问Meteor.userId()并得到正确的login用户的ID。 也尝试通过Meteor.users.findOne()访问用户,但没有成功。

我的问题是,为什么用户对象是未定义的,虽然用户ID是可访问的?

我用下面的代码片段来testing:

 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 

Meteor.user()确实不是直接可用的,你可以尝试以下方法:

 Tracker.autorun(function(){ 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); }); 

这应该首先打印未定义,然后打印正确的用户。

Meteor.userId()在login时立即可用。 Meteor.user()要求对象通过DDP传递给客户端,所以不能立即使用。

默认情况下, profile键被发布。 由于您closures了自动发布,因此您可能需要从用户发布自己的特定密钥集。

我通常有:

服务器:

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

客户:

 Meteor.subscribe('me'); 

您也可以发布有关其他用户的信息,但在那里要共享的密钥列表通常要小得多。 例如,您通常不想与login用户共享其他用户的电子邮件地址。