mongodb supports 1:n relations which is nested (embedded) document.
Unfortunately, that’s one area where Meteor limits you. Meteor’s livedata
package diffs collection changes on the topmost fields of a document, therefore if you embed another document, the changes to those documents will not be equipped with fine grained reactivity. Furthermore, any change to any embedded document will invalidate the parent collection’s computations.
Therefore, in Meteor world, you do 1:n
relationships with (app based) joins.
For that, you can make use of packages such as dburles:collection-helpers
and reywood:publish-composite
A very basic example would be:
Common.js
// Let's create the collection on both the server and the client
Posts = new Mongo.Collection('posts');
Comments = new Mongo.Collection('comments');
// Now let's define some helpers (transforms) that fetch the related documents
Posts.helpers({
// Join the comments cursor to the post
comments: function() {
return Comments.find({postId: this._id})
},
// Join the user profile on the poster's user id
authorName: function() {
var userProfile = Meteor.users.findOne({_id: this.posterUserId}).profile;
return userProfile.name + ' ' + userProfile.lastName;
}
});
Server.js
// Let's publish all the posts as well as their comments
Meteor.publishComposite('postsWithComments', function() {
return {
find: function() {
return Posts.find();
},
children: [
{
find: function(post) {
return post.comments();
}
}
]
};
});
// Let's insert a dummy post and a dummy comment, both from the same user
Meteor.startup(function() {
postId = Posts.insert({title: 'My first post', content: 'Some awesome post content', posterUserId: Meteor.userId()});
Comments.insert({postId: postId, body: 'Congrats to myself on my first post.', commenterUserId: Meteor.userId()})
});
Client.js
// Let's subscribe to the publication
Meteor.subscribe('postsWithComments');
Having declared these, we should be getting
Browser console
Console.log(Posts.findOne().title) //=> My first post
Console.log(Posts.findOne().comments().fetch()[0]) //=> Congrats to...
Console.log(Posts.findOne().authorName) //=> First and last name of the user
We could also have published user data, joined the comment author name and published that as well etc. But I’ll leave that to you as exercise 