Nubby
Nubby

Reputation: 157

Meteor takes multiple times to make a successful database read

Say I have a helper that needs to return an article's title.

<template name="articleList">
    <span>{{title}}</span>
</template>

Template.articleList.title = function () {
   return Articles.findOne({author: "Billy Bob"}).title
}

I often get a 'Cannot read property title of undefined' error. So when I try to debug it like this

Template.articleList.title = function () {
   console.log(Articles.findOne({author: "Billy Bob"}))
}

The log will say

undefined
undefined
Object[0]

So it only works on the third time. I think it's probably bad code somewhere in my router or somewhere else, but I don't know what it is. Any suggestions?

Upvotes: 0

Views: 60

Answers (2)

sbking
sbking

Reputation: 7680

You need to check that the document is already loaded by your subscription. Try this:

<template name="articleList">
    <span>{{title}}</span>
</template>
Template.articleList.title = function () {
    var doc = Articles.findOne({author: "Billy Bob"});
    return doc && doc.title;
};

The reason is that if the client hasn't yet received the document over DDP, the findOne call will return null. You get an error when you try to call null.title.

Upvotes: 1

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

Try this:

<template name="articleList">
    <span>{{article.title}}</span>
</template>

Template.articleList.article = function () {
   return Articles.findOne({author: "Billy Bob"});
}

Upvotes: 0

Related Questions