[英]Meteor & MongoDB. Troubles with getting data from collection (finding documents between two dates)
[英]Having troubles with getting data from Meteor collection
有人可以向我解释一下吗:如果我正在浏览器的控制台中从集合中获取数据,则可以正常工作,但同时呈现模板(使用相同集合)时,它会引发异常,如查询结果为空。 我究竟做错了什么?
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
, .threads
不会返回任何内容, .threads
不会读取.threads
因此不会出现异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.