简体   繁体   中英

Cannot read property 'profile' of undefined in meteor.JS function?

I have the following code:

Template.analyze.userFullName = function() {
    var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}});
    return u.profile.name;
};

Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}}) returns the following when used in the console:

Object
    _id: "79ef0e67-6611-4747-b669-45cc163cc1d8"
    profile: Object
        name: "My Name"

But when I use it in code above I get this: Uncaught TypeError: Cannot read property 'profile' of undefined

Why is this happening? All I want to do is retrieve the user's full name in their profile and pass it to a template part.

The Template is being rendered immediately on pageload when the user is not available yet, which is causing an error. Thankfully since you're using the Users collection, which is reactive, you can just have it re-render when it becomes available. You do this by checking first if the object is not null:

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

This way, when the user is null (during load) the Template won't throw an error. Immediately upon the data being available, the reactivity will invoke the template again, and it will render on the screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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