简体   繁体   English

从流星收集中获取数据时遇到麻烦

[英]Having troubles with getting data from Meteor collection

Can someone explain this thing to me: if I'm getting data from a collection in browser's console, it works fine, but at the same time when a template (which uses the same collection) is being rendered it throws an exception as the query result is empty. 有人可以向我解释一下吗:如果我正在浏览器的控制台中从集合中获取数据,则可以正常工作,但同时呈现模板(使用相同集合)时,它会引发异常,如查询结果为空。 What am I doing wrong? 我究竟做错了什么?

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]

Other templates that use the same collection work fine, though 尽管使用相同集合的其他模板也可以正常工作

When Meteor initially loads on the browser it wont yet have the data from the collections from the server. 当Meteor最初在浏览器上加载时,它不会再包含来自服务器的集合中的数据。

It takes a very short amount of time for them to be available. 它们仅需很短的时间即可使用。 So you just need to handle the case where there is no result provided. 因此,您只需要处理没有提供结果的情况。 When the data arrives reactivity should update all your templates with the new data. 数据到达后,反应性应使用新数据更新所有模板。

You can use something like: 您可以使用类似:

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

findOne is a shorter version of find().fetch[0] . findOnefind().fetch[0] So if there isn't a result ie null nothing is returned and .threads wont be read so there wouldn't be an exception. 因此,如果没有结果,即null.threads不会返回任何内容, .threads不会读取.threads因此不会出现异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM