Exception in template helper

I have created a field called “categories” in my Meteor.users() collection upon their registration. For development purposes I made the field visible from the console if i did Meteor.users().find.fetch() in the console. I also published and subscribed to it.

The “categories” fields in the Meteor.users collection is an array which has multiple category objects. What i am trying to do is get the name which is inside each object in the categories array but while is works (the names are displayed in the browser), i keep getting this exception:

Exception in template helper: TypeError: Cannot read property ‘categories’ of undefined

with a more junk following it. it also says it is in debug.js.41 which seems to be a meteor file i’m guessing

Here’s my code:

In the event.js file:


categories: function() {
    // console.log(Meteor.users.find({_id: Meteor.userId()}).fetch()[0].categories);
    return Meteor.users.find({_id: Meteor.userId()}).fetch()[0].categories; //

In the publications.js (server folder):

Meteor.publish("theUsers", function() {
  return Meteor.users.find({_id: this.userId}, {fields: {categories: 1, joined: 1, email: 1}});

Here’s what my Meteor.users collection look like:

I want to be the name (in this case “To-Do”) which is in the object inside of the “categories” array.

If i type,

Meteor.users.find({_id: Meteor.userId()}).fetch()[0].categories;

in the console it returns the array with the objects inside but it when i place it in my code it gives me that exception and I don’t know why.

Can someone help me with this one.
Thank you in advance.

p.s. let know if i should post more code.

My guess is that Meteor.subscribe("theUsers") is executed without problems, but before you have received any documents from this subscription, the helper categories runs, where you try to read the categories property from a user. However, you haven’t received any users yet, so ...fetch()[0] will evaluate to undefined.

Later, when you try the same expression in the console, you have received the documents, and the expressions evaluates to what’s expected.

Hey thank you for the reply,

So I would have to check if the publish is ready first? Would I have to use this.ready() in the publication function, is that it?

Yea, that’s the way one should do it. Or use subscribe on the template instance. Or use a guard:

let user = Meteor.users.findOne({_id: Meteor.userId()})
return user && user.categories