Accessing documents using parameters in a helper


#1

In my HTML file I wan’t to be able to call something like {{fromCategory myVariable keyFromDocument}} without having to use each loops.

I tried doing it like this

Template.registerHelper('fromCategory', (id, key) => {
    return Categories.findOne({_id:id}).key;
});

And like this

Template.registerHelper('fromCategory', (id, key) => {
    return Categories.find({_id:id}, {fields: {key:1}}).fetch()[0];
});

But neither works and now I’m out of ideas. Any suggestions on how I can accomplish this?


#2

Use square bracket notation:

Template.registerHelper('fromCategory', (id, key) => {
    return Categories.findOne({_id:id})[key];
});

And like this for a computed property

Template.registerHelper('fromCategory', (id, key) => {
    return Categories.find({_id:id}, {fields: {[key]:1}}).fetch()[0];
});

#3

@coagmano Thanks for the input, it seem to be working fine now.

There’s just one problem, in the console it prints
Exception in template helper: TypeError: Cannot read property 'name' of undefined
for
{{fromCategory 'name' this.category}}
Even though it prints the name correctly, this error seem to show up anyway.

Template.registerHelper('fromCategory', (key, id) => {
    return Categories.findOne({_id:id})[key];
});

#4

That means that findOne is returning undefined. AKA it can’t find a document with the _id you’ve specified.

Check that you are passing in the _id of the category and not it’s name.
And change your helper to handle the case where it can’t find the category by _id:

Template.registerHelper('fromCategory', (key, id) => {
    const category = Categories.findOne({_id:id});
    return category ? category[key] : null;
})

#5

Forgot I could use that expression. Thanks!