简体   繁体   中英

Meteor.user().profile returns 'profile' undefined

I have a helper called 'isActive' and a template named 'create'.. see below

Template.create.isActive = function () {
  return Meteor.user().profile.isActive;
};

When I try to run this code it returns the following in console: "Exception in template helper: TypeError: Cannot read property 'profile' of undefined".

Basically I want to pull the 'isActive' info from the current user profile and return it to the template. Any idea why this does not work?

Update

//startup on server side:
Meteor.publish("userData", function() {
  if (this.userId) {
    return Meteor.users.find({_id: this.userId},
      {fields: {'profile.isActive': 1}});
  } else {
    this.ready();
  }
});

//startup on client side
Meteor.subscribe('userData');

//router
this.route('list', {
  path: 'list',
  waitOn : function () {
    return Meteor.subscribe('userData');
  },
  data : function () {
    return Meteor.users.findOne({_id: this.params._id});
  },
  action : function () {
    if (this.ready()) {
      this.render();
    }
  }
});

Meteor.user() is undefined. You are either not logged in with any user or your template is rendered before the users collection is synced to the client. If you use a router like iron router you can wait for the collection being available or for the user being logged on.

Without using a router the easiest would be to check if the user is defined:

Template.create.isActive = function () {
    return Meteor.user() && Meteor.user().profile.isActive;
}

Since Meteor.user() is reactive the template will be rerendered when the user changes, ie when it is available.

This is a common error btw, see also:

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