meteor-publish-composite
publishComposite(...)
provides a flexible way to publish a set of related documents from various collections using a reactive join. This makes it easy to publish a whole tree of documents at once. The published collections are reactive and will update when additions/changes/deletions are made.
Project
This project differs from many other parent/child relationship mappers in its flexibility. The relationship between a parent and its children can be based on almost anything. For example, let's say you have a site that displays news articles. On each article page, you would like to display a list at the end containing a couple of related articles. You could use publishComposite
to publish the primary article, scan the body for keywords which are then used to search for other articles, and publish these related articles as children. Of course, the keyword extraction and searching are up to you to implement.
Found a problem with this package? See below for instructions on reporting.
Installation
$ meteor add reywood:publish-composite
Usage
This package exports a function on the server:
publishComposite(name, options)
Arguments
-
name
-- stringThe name of the publication
-
options
-- object literal or callback functionAn object literal specifying the configuration of the composite publication or a function that returns said object literal. If a function is used, it will receive the arguments passed to
Meteor.subscribe('myPub', arg1, arg2, ...)
(much like thefunc
argument ofMeteor.publish
). Basically, if your publication will take no arguments, pass an object literal for this argument. If your publication will take arguments, use a function that returns an object literal.The object literal must have a
find
property, and can optionally havechildren
andcollectionName
properties.-
find
-- function (required)A function that returns a MongoDB cursor (e.g.,
return Meteor.users.find({ active: true });
) -
children
-- array (optional) or function- An array containing any number of object literals with this same structure
- A function with top level documents as arguments. It helps dynamically build
the array based on conditions ( like documents fields values)
-
collectionName
-- string (optional)A string specifying an alternate collection name to publish documents to (see this blog post for more details)
Example:
1{ 2 find() { 3 // Must return a cursor containing top level documents 4 }, 5 children: [ 6 { 7 find(topLevelDocument) { 8 // Called for each top level document. Top level document is passed 9 // in as an argument. 10 // Must return a cursor of second tier documents. 11 }, 12 children: [ 13 { 14 collectionName: 'alt', // Docs from this find will be published to the 'alt' collection 15 find(secondTierDocument, topLevelDocument) { 16 // Called for each second tier document. These find functions 17 // will receive all parent documents starting with the nearest 18 // parent and working all the way up to the top level as 19 // arguments. 20 // Must return a cursor of third tier documents. 21 }, 22 children: [ 23 // Repeat as many levels deep as you like 24 ] 25 } 26 ] 27 }, 28 { 29 find(topLevelDocument) { 30 // Also called for each top level document. 31 // Must return another cursor of second tier documents. 32 } 33 // The children property is optional at every level. 34 } 35 ] 36}
Example with children as function:
1{ 2 find() { 3 return Notifications.find(); 4 }, 5 children(parentNotification) { 6 // children is a function that returns an array of objects. 7 // It takes parent documents as arguments and dynamically builds children array. 8 if (parentNotification.type === 'about_post') { 9 return [{ 10 find(notification) { 11 return Posts.find(parentNotification.objectId); 12 } 13 }]; 14 } 15 return [ 16 { 17 find(notification) { 18 return Comments.find(parentNotification.objectId); 19 } 20 } 21 ] 22 } 23}
-
Examples
Example 1: A publication that takes no arguments.
First, we'll create our publication on the server.
1// Server 2import { publishComposite } from 'meteor/reywood:publish-composite'; 3 4publishComposite('topTenPosts', { 5 find() { 6 // Find top ten highest scoring posts 7 return Posts.find({}, { sort: { score: -1 }, limit: 10 }); 8 }, 9 children: [ 10 { 11 find(post) { 12 // Find post author. Even though we only want to return 13 // one record here, we use "find" instead of "findOne" 14 // since this function should return a cursor. 15 return Meteor.users.find( 16 { _id: post.authorId }, 17 { fields: { profile: 1 } }); 18 } 19 }, 20 { 21 find(post) { 22 // Find top two comments on post 23 return Comments.find( 24 { postId: post._id }, 25 { sort: { score: -1 }, limit: 2 }); 26 }, 27 children: [ 28 { 29 find(comment, post) { 30 // Find user that authored comment. 31 return Meteor.users.find( 32 { _id: comment.authorId }, 33 { fields: { profile: 1 } }); 34 } 35 } 36 ] 37 } 38 ] 39});
Next, we subscribe to our publication on the client.
1// Client 2Meteor.subscribe('topTenPosts');
Now we can use the published data in one of our templates.
<template name="topTenPosts"> <h1>Top Ten Posts</h1> <ul> <li> -- </li> </ul> </template>
1Template.topTenPosts.helpers({ 2 posts() { 3 return Posts.find({}, { sort: { score: -1 }, limit: 10 }); 4 }, 5 6 postAuthor() { 7 // We use this helper inside the {{#each posts}} loop, so the context 8 // will be a post object. Thus, we can use this.authorId. 9 return Meteor.users.findOne(this.authorId); 10 } 11})
Example 2: A publication that does take arguments
Note a function is passed for the options
argument to publishComposite
.
1// Server 2import { publishComposite } from 'meteor/reywood:publish-composite'; 3 4publishComposite('postsByUser', function(userId, limit) { 5 return { 6 find() { 7 // Find posts made by user. Note arguments for callback function 8 // being used in query. 9 return Posts.find({ authorId: userId }, { limit: limit }); 10 }, 11 children: [ 12 // This section will be similar to that of the previous example. 13 ] 14 } 15});
1// Client 2var userId = 1, limit = 10; 3Meteor.subscribe('postsByUser', userId, limit);
Example 3: A publication from async function
Note a function is passed for the options
argument to publishComposite
.
1// Server 2import { publishComposite } from 'meteor/reywood:publish-composite'; 3 4publishComposite('postsByUser', async function(userId) { 5 const user = await Users.findOneAsync(userId) 6 const limit = user.limit 7 8 return { 9 find() { 10 // Find posts made by user. Note arguments for callback function 11 // being used in query. 12 return Posts.find({ authorId: userId }, { limit: limit }); 13 }, 14 children: [ 15 // This section will be similar to that of the previous example. 16 ] 17 } 18});
Known issues
Avoid publishing very large sets of documents
This package is great for publishing small sets of related documents. If you use it for large sets of documents with many child publications, you'll probably experience performance problems. Using this package to publish documents for a page with infinite scrolling is probably a bad idea. It's hard to offer exact numbers (i.e. don't publish more than X parent documents with Y child publications) so some experimentation may be necessary on your part to see what works for your application.
Arrow functions
You will not be able to access this.userId
inside your find
functions if you use arrow functions.
Testing
Run the following:
meteor test-packages reywood:publish-composite --driver-package meteortesting:mocha
The tests are executing a combination of methods and subscriptions. The quickest option was to add a pause after each
operation (see usage of sleep()
in ./tests/server.js
), to allow for the publications to send down all the
documents. However, this is flaky, so you may want to refresh the browser if you notice tests failing for no
apparent reason.
Reporting issues/bugs
If you are experiencing an issue with this package, please create a GitHub repo with the simplest possible Meteor app that demonstrates the problem. This will go a long way toward helping me to diagnose the problem.
More info
For more info on how to use publishComposite
, check out these blog posts:
Note that these articles use the old pre-import notation, Meteor.publishComposite
, which is still available for backward compatibility.
Alternatives
While we are happy that you find this package of value, there are limitations, especially on high traffic applications. There are also other solutions that can solve the problems that publish-composite solves, so here is a list of possible alternatives:
MongoDB Aggregations
MongoDB itself has a functionality called Aggregations which allows you to combine data from multiple collections into one document. It also has other useful features that you can utilize. The downside is that unless you use reactive-aggregate package the aggregations are not reactive and things it is not the easiest to learn or master.
GraphQL
GraphQL allows you to specify exactly which data you need and even embed child documents. Apollo GraphQL also has an official package
and there is the apollo
starter skeleton in Meteor itself to get you started quickly.
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!