Created
July 5, 2015 20:31
-
-
Save Pushplaybang/f9b949b4e00d2a54c389 to your computer and use it in GitHub Desktop.
Meteor reactive publication across collections (essentially a join)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// on the server | |
Meteor.publish('comments', function(id) { | |
check(id, String); | |
var sub = this, userHandles = [], commentsHandle = null, userCursor; | |
// send over the author for the comment | |
var publishCommentAuthor = function publishCommentAuthor(authorId) { | |
userCursor = Meteor.users.find({ _id: authorId}); | |
userHandles[authorId] = | |
Mongo.Collection._publishCursor(userCursor, sub, 'users'); | |
}; | |
commentsHandle = Comments.find({ | |
mediaId: id | |
}, { | |
sort: { createdAt: -1} | |
}).observeChanges({ | |
added: function(id, post) { | |
// publish the new user record | |
publishCommentAuthor(post.createdBy); | |
// add the new post to the publication | |
sub.added('comments', id, post); | |
}, | |
changed: function(id, fields) { | |
// update the comment if it changed | |
sub.changed('comments', id, fields); | |
}, | |
removed: function(id) { | |
// get the author | |
var authorId = Comments.findOne(id).createdBy; | |
// stop observing changes on the comments author | |
userHandles[authorId] && userHandles[authorId].stop(); | |
// delete the comment | |
sub.removed('comments', id); | |
} | |
}); | |
sub.ready(); | |
/* make sure we clean everything up (note `_publishCursor` | |
does this for us with the user observers) */ | |
sub.onStop(function() { commentsHandle.stop(); }); | |
}); | |
/* | |
This example gets the user objects related to comments for a post. | |
the id received by the publication from the subscription is the id of the post | |
that the comments belong to. We then run a function each time a document is added | |
to the comments array to get the associated user record, and leveraging the | |
'_publishCursor' method this gets added to the users collection. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment