【问题标题】:Meteor Iron Router Not Passing MongoDB Collection Data into TemplateMeteor Iron Router 没有将 MongoDB 集合数据传递到模板中
【发布时间】:2015-04-11 11:53:06
【问题描述】:

我使用 Iron Router 包创建了一个基本的 Meteor 应用程序。在 MongoDB 数据库中植入一些数据,并尝试告诉 Iron Router 将集合提供给模板。但是数据没有进入模板。

/collections.js

Wip = new Mongo.Collection('wip');

/app.js

Router.configure({
  layoutTemplate: 'masterLayout'
});
Router.route('wip2', {
  path: '/wip2/:shortname',
  template: 'wip2',
  data: function() {
    return Wip.findOne( { shortname: this.params.shortname } );
  }
});

在那里您可以看到集合查询。在 wip2.html 文件中,我有像 {{name}} 和 {{shortname}} 这样的变量,但它们都没有显示任何内容。我通过在服务器上执行“meteor mongo”并运行查找来确认本地 MongoDB 确实有数据:

db.wip.findOne( {shortname : 'JonSmith'} );

MongoDB 确实返回数据,如下所示:

{
  "shortname" : "JonSmith",
  "name" : "Jon Smith"
}

为了确认 Iron Router 实际上可以将数据传递到模板中,我可以对数据进行硬编码,从而成功地将数据传递到模板中:

/app.js

Router.route('wip2', {
  path: '/wip2/:shortname',
  template: 'wip2',
  data: {
    shortname: "JonSmith",
    name:   "John Smith"
  }
});

这行得通。 wip2.html 中的 {{shortname}} 和 {{name}} 确实提供了值。

关于为什么没有将 Collection 结果提供到模板中的任何想法?提前致谢!

【问题讨论】:

  • 您订阅了集合中的文档吗?
  • 不确定您的意思,但我尝试在路由下的 app.js 中添加这样的订阅,但模板会永远等待“正在加载...”,但没有任何反应。 `waitOn: function() { return Meteor.subscribe('wip', this.params.shortname); },`
  • 是的,您还需要在服务器上调用Meteor.publish,并使用适当的参数。如果没有这种发布/订阅机制,客户端的集合将不包含任何文档(除非您添加了 autosubscribe 包。
  • 谢谢。发布确实解决了这个问题。问题,如果我在服务器上的发布功能上执行return Wip.find();,这是否意味着客户端可以访问集合中的所有记录?如何将他们允许的可订阅结果集限制为他们允许的记录?
  • 是的,在发布函数中返回Wip.find()会将集合中的所有文档发送给客户端。将选择器传递给 find 以将其限制为仅匹配选择器的文档。 this.userId 将引用客户端的用户 ID。使用它来创建一个仅匹配用户应该有权访问的文档的选择器。

标签: meteor iron-router


【解决方案1】:

你能试试这个代码吗,

Router.route('wip2', {
  path: '/wip2/:shortname',
  template: 'wip2',
  data: function() {
    templateData = {
        Wip : Wip.find( { shortname: this.params.shortname },{limit : 1} );
     };
  return templateData;
  }
});

findOne 只返回一个对象,而 findlimit = 1 将返回光标,您可以随意使用它。

【讨论】:

    猜你喜欢
    • 2015-06-05
    • 2014-05-30
    • 2014-01-04
    • 1970-01-01
    • 2013-09-10
    • 2015-08-31
    • 2015-10-30
    • 2014-12-28
    • 2014-05-19
    相关资源
    最近更新 更多