Meteor.user collection helper returns undefined

I am storing a lot of custom user information in a own collection Profile. I now want to create a collection helper for the Meteor.user() object, which returns the correct profile dataset.

I’ve created the collection helper:

Meteor.users.helpers({
  getProfile() {
    return Profile.findOne({ _id: this.profileId });
  },
});

Ideally I’d like to access the current users profile fields globally like that (for instance in Template helpers):

Meteor.user().getProfile().fieldName;

That works… after a while!

However sometimes the Profile collection does not seem to be ready and I get an undefined in return. In that cases the getProfile() helper will be called several times and at one point will return the value I try to access, but until then it throws exceptions:

Exception in template helper: TypeError: Cannot read property 'fieldName' of undefined

Any ideas on how I could prevent that?

Easiest way with minimum modifications would be to return an empty object if sub not ready. Should work unless you have nested fields in your profile in which case you can stub them in your placeholder object.

Meteor.users.helpers({
  getProfile() {
    return Profile.findOne({ _id: this.profileId }) || {};
  },
});

That works like a charm! I have to stub the nested objects and it’s probably not the prettiest way, but as long as it works I’m fine with it. Thanks a lot!