【问题标题】:One to Many Relationship (or NoSQL Mongo equivalent to it) in Meteor CollectionsMeteor Collections 中的一对多关系(或 NoSQL Mongo 等价物)
【发布时间】:2014-01-23 21:13:21
【问题描述】:

我是 Mongo 和 NoSQL 数据库的新手。有人可以解释一下在 Meteor 中进行一对多加入和循环浏览集合的方法吗?

例如,假设我有两个集合,一个帖子和一个评论,其中每个评论都有一个 postId,这意味着每个帖子都有零个或多个评论。我对 Meteor 的这种情况的最佳实践很感兴趣,特别是您可以循环浏览每个帖子并在嵌套的 Handlebars 调用中发表评论。类似于下面的示例:

{{#each post}}
  {{title}}
  {{content}}
  {{#each comment}}
    {{comment_text}} by {{author}}
  {{/each}}
{{/each}}

【问题讨论】:

  • mongodb不支持join。 mongodb 方式是将 cmets 嵌入到 post 文档中。在education.mongodb.com 上有一个在线课程,他们将引导您完成以下操作:在 mongodb 之上构建博客

标签: mongodb meteor handlebars.js


【解决方案1】:

虽然标准的 MongoDB 范例是对数据进行非规范化,但在 Meteor 应用程序中,坚持为每个逻辑数据集拥有不同集合(表)的模式并不少见。

要在 Meteor webapps 中实现连接,您只需定义两个集合之间的关系:

var postId = Posts.insert({
  title: "A post",
  content: "Some content..."
});

Comments.insert({
  postId: postId,
  author: "Someone",
  text: "Some text..."
});

反规范化意味着你不能忘记发布这两个集合,你可以这样做:

Meteor.publish("postById", function(postId){
  // publish the according post...
  var postCursor = Posts.find(postId);
  // ...and every comments associated
  var commentsCursor = Comments.find({
    postId: postId
  });
  // you can return multiple cursors from a single publication
  return [postCursor, commentsCursor];
});

此出版物将向客户发送一个帖子及其所有 cmets,给定一个 post._id。 与正确的客户端路由相关联,您可以使用从 URL (/posts/:_id) 检索到的帖子 ID 订阅此发布,并显示帖子及其所有 cmets。

您的模板伪代码没问题,但是我会为每个集合使用不同的模板重构它。

HTML

<template name="outer">
  {{!-- loop through each post, the child template will
        be using the current post as data context --}}
  {{#each posts}}
      {{> post}}
  {{/each}}
</template>

JS

Template.outer.helpers({
  posts: function(){
    return Posts.find();
  }
});

HTML

<template name="post">
  <h3>{{title}}</h3>
  <p>{{content}}</p>
  {{!-- loop through each comment and render the associated template --}}
  {{#each comments}}
    {{> comment}}
  {{/each}}
</template>

JS

Template.posts.helpers({
  comments: function(){
    // return every comment belonging to this particular post
    // here this references the current data context which is
    // the current post being iterated over
    return Comments.find({
      postId: this._id
    });
  }
});

HTML

<template name="comment">
  <p>{{text}}</p>
  <span>by {{author}}</span>
</template>

【讨论】:

  • 感谢您的精彩回答以及重构模板的建议。
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2015-04-05
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
相关资源
最近更新 更多