流星userId存在,但用户未定义



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

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

我使用以下代码片段进行测试:
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.userId()在登录时立即可用。Meteor.user()要求对象通过DDP传递到客户端,所以它不是立即可用的。

默认发布profile密钥。由于您已经关闭了自动发布,您可能希望从用户发布您自己的特定密钥集。

我通常有:

服务器:

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

Meteor.subscribe('me');

您也可以发布关于其他用户的信息,但是要共享的密钥列表通常要小得多。例如,您通常不希望与登录用户共享其他用户的电子邮件地址。

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);  
});

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

最新更新