Javascript 无法读取属性';简介';meteor.JS函数中未定义的?

Javascript 无法读取属性';简介';meteor.JS函数中未定义的?,javascript,meteor,Javascript,Meteor,我有以下代码: Template.analyze.userFullName = function() { var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}}); return u.profile.name; }; Meteor.users.findOne({u-id:this.userId},{fields:{name:1}})在控制台中使用时返回以下内容: Object _id: "

我有以下代码:

Template.analyze.userFullName = function() {
    var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}});
    return u.profile.name;
};
Meteor.users.findOne({u-id:this.userId},{fields:{name:1}})
在控制台中使用时返回以下内容:

Object
    _id: "79ef0e67-6611-4747-b669-45cc163cc1d8"
    profile: Object
        name: "My Name"
但是当我在上面的代码中使用它时,我得到了这样的结果:
uncaughttypeerror:无法读取未定义的属性“profile”


为什么会这样?我所要做的就是在他们的配置文件中检索用户的全名,并将其传递给模板部件。

当用户不可用时,模板会立即在pageload上呈现,这会导致错误。谢天谢地,因为您使用的是用户集合,它是被动的,所以当它可用时,您可以让它重新渲染。您可以通过首先检查对象是否为null来执行此操作:

Template.analyze.userFullName = function() {
    // use Meteor.user() since it's available
    if (Meteor.user())
      return Meteor.user().profile.name;
};

这样,当用户为null(在加载期间)时,模板不会抛出错误。一旦数据可用,反应性将立即再次调用模板,并在屏幕上呈现。

我假设无论您如何获取用户集合,调用
Template.analyze.userFullName
时,还没有完成从服务器获取数据。@Vinay我正在使用发布和订阅功能获取用户集合。在检索之前,我应该如何检查它是否已完成下载?请看
观察
:谢谢,我会看的。Rahul,你太棒了。谢谢大家对流星的帮助!这里有一个有趣的错误。如果我从注销状态开始,然后登录,应用程序会识别并更改页面,并且工作正常。但是如果我在登录时刷新,它会再次抛出错误。无需担心,只需在返回解决问题之前添加
if(!Meteor.logging())
check即可。谢谢Rahul。这有助于:)