Publishing custom data

Philipp Muens
2 min readNov 18, 2015

--

Meteor publications are a great way to push data down from the server to the client.
But this data is not bound / limited to MongoDB related data. You can publish nearly anything you want.

This blog post will show you how you can write a publication which will publish custom / static data.

Publishing static content

Let’s pretend we have an application where we want to display static content together with dynamic content.
We could hard code the static content in the template but our long term goal is the replacement of the static content fetching with a fetching from the MongoDB rather than an array (as you can see in the code below). This switch should be implemented without many code changes later on.

Let’s start with the definition of the collection which will manage our static content:

// On the client and the server<br />
StaticContents = new Mongo.Collection('staticContents');<br />

Next up we write a publication which will provide our static content:

// On the server<br />
Meteor.publish('staticContents', function () {<br />
let publication = this;</p>
<p> // Our static contents as objects inside an array<br />
let staticContents = [<br />
{<br />
title: 'Imprint',<br />
body: 'Imprint content'<br />
},<br />
{<br />
title: 'Contact',<br />
body: 'Contact content'<br />
}<br />
];</p>
<p> // Iterate over the static contents and add them to the publication<br />
staticContent.forEach((staticContent) => {<br />
publication.added('staticContents', Random.id(), staticContent);<br />
});</p>
<p> // Mark the publication as ready (so that the clients know when all data is available)<br />
publication.ready();<br />
});<br />

That’s it. We are now able to subscribe to the staticContents publication and access the data through our StaticContents collection.

If we decide to serve our static contents from a MongoDB we simply need to fetch the data from the database in the publication rather than providing it in the form of an array. No need to touch any code on the client side!

Another great scenario is the “timeline problem” which is discussed in detail here.
It deals with the problem of displaying sorted entries from different collections in one place (like the Facebook timeline where different activities from different data sources are displayed in an ordered fashion).

Additional resources

--

--

Philipp Muens
Philipp Muens

Written by Philipp Muens

👨‍💻 Maker — 👨‍🏫 Lifelong learner — Co-creator of the Serverless Framework — https://philippmuens.com

Responses (1)