Javascript 从流星收集中获取数据有困难

Javascript 从流星收集中获取数据有困难,javascript,meteor,Javascript,Meteor,有人能给我解释一下吗:如果我从浏览器控制台中的集合中获取数据,它可以正常工作,但在呈现模板(使用相同集合)的同时,由于查询结果为空,它会引发异常。我做错了什么 Hubs = new Meteor.Collection("hubs"); Meteor.subscribe("hubs"); Template.thread.posts = function() { var hubName = 'foo', thread = Session.get("currentThread"

有人能给我解释一下吗:如果我从浏览器控制台中的集合中获取数据,它可以正常工作,但在呈现模板(使用相同集合)的同时,由于查询结果为空,它会引发异常。我做错了什么

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]

其他使用相同集合的模板也可以正常工作,不过当Meteor最初加载到浏览器上时,它还没有服务器上集合的数据

它们的可用时间非常短。所以你只需要处理没有结果的情况。当数据到达时,您应该使用新数据更新所有模板

您可以使用以下内容:

hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;
findOne
find().fetch[0]
的较短版本。因此,如果没有结果,即
null
不会返回任何内容,并且
不会读取
。线程
,因此不会出现异常