Meteor Collections中的一对多关系(或NoSQL Mongo相当于它)

JAM*_*Eco 6 mongodb handlebars.js meteor

我是Mongo和NoSQL数据库的新手.有人可以解释在Meteor中进行一对多加入和循环收集的方式.

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

{{#each post}}
  {{title}}
  {{content}}
  {{#each comment}}
    {{comment_text}} by {{author}}
  {{/each}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

sai*_*unt 14

尽管标准的MongoDB范例是对数据进行非规范化,但在Meteor应用程序中,坚持使用每个逻辑数据集具有不同集合(表)的模式并不罕见.

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

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

Comments.insert({
  postId: postId,
  author: "Someone",
  text: "Some text..."
});
Run Code Online (Sandbox Code Playgroud)

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

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];
});
Run Code Online (Sandbox Code Playgroud)

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

您的模板伪代码是正常的,但我会使用每个集合的不同模板重构它.

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>
Run Code Online (Sandbox Code Playgroud)

JS

Template.outer.helpers({
  posts: function(){
    return Posts.find();
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML

<template name="post">
  <h3>{{title}}</h3>
  <p>{{content}}</p>
  {{!-- loop through each comment and render the associated template --}}
  {{#each comments}}
    {{> comment}}
  {{/each}}
</template>
Run Code Online (Sandbox Code Playgroud)

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
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML

<template name="comment">
  <p>{{text}}</p>
  <span>by {{author}}</span>
</template>
Run Code Online (Sandbox Code Playgroud)