【问题标题】:Meteor userId is present but user is undefinedMeteor userId 存在但用户未定义
【发布时间】:2017-03-20 23:23:02
【问题描述】:

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

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

我使用以下代码sn-p进行测试:

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 

【问题讨论】:

  • 你是在服务器端、客户端还是同时运行代码?
  • 仅在客户端运行
  • 你有没有从服务器相应的发布来检索用户的数据?
  • 不,没有订阅任何特定的出版物。我还删除了自动发布包。我是否需要订阅才能获得已登录的 it 用户?

标签: javascript node.js meteor meteor-accounts


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-29
      • 2021-06-18
      • 2014-09-16
      • 2015-04-19
      • 2012-12-05
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多