【问题标题】:Having troubles with getting data from Meteor collection从 Meteor 集合中获取数据时遇到问题
【发布时间】:2013-04-20 16:04:12
【问题描述】:

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

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]

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

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

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

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

    你可以使用类似的东西:

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

    findOnefind().fetch[0] 的较短版本。因此,如果没有结果,即 null 不会返回任何内容,并且不会读取 .threads,因此不会出现异常。

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2020-01-25
      • 2020-07-13
      • 2020-08-05
      • 2017-06-12
      • 2013-09-27
      相关资源
      最近更新 更多