从Meteor集合中获取数据时遇到麻烦

时间:2013-04-20 16:04:12

标签: javascript meteor

有人可以向我解释这个问题:如果我从浏览器控制台的集合中获取数据,它可以正常工作,但同时当渲染模板(使用相同的集合)时会抛出异常因为查询结果为空。我做错了什么?

Hubs = new Meteor.Collection("hubs");
Meteor.subscribe("hubs");
Template.thread.posts = function() {
    var hubName = 'foo',
        thread = Session.get("currentThread"),
        hub = Hubs.find({ name: hubName }).fetch()[0];
//throws: "Uncaught TypeError: Cannot read property 'threads' of undefined "
    return hub.threads[thread].posts;
}

//this being executed in browser's console yeilds an object:
Hubs.find({name: 'foo'}).fetch()[0]

使用相同集合的其他模板可以正常工作,但

1 个答案:

答案 0 :(得分:1)

当Meteor最初在浏览器上加载时,它还没有来自服务器集合的数据。

它们需要很短的时间才能使用。所以你只需要处理没有提供结果的情况。当数据到达时,反应性应使用新数据更新所有模板。

您可以使用以下内容:

hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;

findOnefind().fetch[0]的缩写版。因此,如果没有结果,即null没有返回任何内容而且.threads不会被读取,那么就不会有例外。

相关问题