虽然标准的 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>