【问题标题】:Meteor - Template from multiple collectionsMeteor - 来自多个集合的模板
【发布时间】:2014-11-26 00:36:32
【问题描述】:

我有两个 mongo 集合:

  • 发帖:{_id: "123", text: "some text", authorid: "456"}
  • 作者:{_id: "456", name: "Cosmo"}

我想显示以下模板:

<template name="Postslist">
  {{#each posts}}
    {{>Post}}
  {{/each}}
</template>

<template name="Post">
  {{text}}
  {{name}}
</template>

所以我创建了一个 Post 助手来显示关联的名称:

Template.Post.helpers({
  name: function() {
    var author = Authors.find({_id: this.authorid});
    return author.name;
  }
});

不幸的是,它没有像我想的那样显示作者姓名。我做错了什么,我应该如何解决这种情况?

我知道我不应该在 NoSQL 数据库中使用外键,但是这些集合是由第 3 方应用程序自动填充的,我无法修改它们。

【问题讨论】:

  • This article 可能会有所帮助。顺便说一句,您是否同时发布/订阅帖子和作者?

标签: javascript mongodb meteor


【解决方案1】:

Find 返回一个 mongo 游标而不是匹配的文档。要从游标中获取匹配的文档,您必须使用 fetch 但是 fetch 不是响应式的。

因此,要解决您的问题并保持反应,您应该返回 findOne 的结果。

Template.Post.helpers({
    getAuthor: function() {
       return Authors.findOne({_id: this.authorid});
    }
});

模板更改:

<template name="Post">
    {{text}}
    {{#with getAuthor}}
        {{name}}
    {{/with}}
</template>

【讨论】:

  • 非常感谢,这是什么解决方案!辉煌而优雅。
猜你喜欢
  • 2015-11-03
  • 2016-09-27
  • 1970-01-01
  • 2015-10-30
  • 2017-03-27
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多