【问题标题】:Meteor returning a field from MongoDB works in console but not in application从 MongoDB 返回字段的 Meteor 在控制台中有效,但在应用程序中无效
【发布时间】:2015-07-18 22:38:20
【问题描述】:

我正在尝试读取我的MongoDB 数据库中的一个文件。在控制台中响应是正确的,而在我的应用程序中出现以下错误:

未捕获的类型错误:无法读取未定义的属性“iati”

我定义了一个模板助手,它应该返回我的 MongoDB 集合中的某个子字段。但是以下似乎不起作用(我得到了前面提到的错误)。

 Template.hello.helpers({
    test: function() {
        return Test.findOne().iati;
    }
});

似乎可行的是返回整个对象:

 Template.hello.helpers({
    test: function() {
        return Test.findOne();
    }
});

然后调用模板内的具体字段:

{{test.iati}}

但是,我想使用 JavaScript 脚本中的数据。我究竟做错了什么?

【问题讨论】:

  • 您的帮助函数在客户端收到集合中的文档之前运行。 Test.findOne() 将评估为undefined,它不具有iati 属性(根据您的错误消息)。当您的助手返回Test.findOne() 的结果并且您在模板中使用{{test.iati}} 时,如果test 具有属性iati{{test.iati}} 将仅显示test.iati(否则它不会显示任何内容)。

标签: mongodb meteor


【解决方案1】:

Tests.findOne() 之类的收集方法会将已获取的文档返回到客户端的 Minimongo 副本。在获取您的文档之前,findOne() 将返回 null。

为了防止这种情况发生,只需在继续计算之前检查帮助程序中的结果:

Template.hello.helpers({
  test: function() {
    if(! Test.findOne()) return;
    return Test.findOne().iati;
  },
});

您也可以在 Iron Router 中等待订阅,以确保加载正确的文档:

this.route('routeName', {
  ...
  onBeforeAction: function() {
    this.subscribe('subscriptionName').wait();
    ...
  },
  ...
});

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多