Skip to content

Meteor.JS observe Collection changes in other apps

In Meteor.JS we can make use of a protocol called DDP (Distributed Data Protocol) which allows us to connect a Meteor app to another Meteor app and share or modify their collections. It also gives us the ability to observe the changes of their collections and react to these changes.

A good use case for me is being able to create a mobile app that would react based on changes being made within a public cloud app, and update the date in the public cloud app from the mobile app. I am able to use Meteor.js for both mobile and desktop because of the Cordova wrapper.

In this simple example, I will connect to an existing Meteor app running on a port, It has a collection named ‘items’ and I want my mobile app to observe these changes and publish the results automatically.

if (Meteor.isClient) {
  // Connect to an app running on port 5000
  var remote = DDP.connect('http://192.168.1.82:5000');
 
  // Get items collection from that app
  Items = new Meteor.Collection('items', remote);
}

In order to observe changes, we want to subscribe to that collection as if we would subscribe to local collections. Then, we can use a method named observe() which allows us to access events such as ‘changed’ and ‘added’.

if (Meteor.isClient) {
 
  // Subscribe to items collection we got via DDP
  remote.subscribe('items', function() {
 
    // Find in items and observe changes
    var items = Items.find().observe({
 
      // When collection changed, find #results element and publish result inside it
      changed:function(res) {
        console.log(res);
        document.getElementById("results").innerHTML = JSON.stringify(res);
      },
      added:function(res) {
        console.log(res);
        document.getElementById("results").innerHTML = JSON.stringify(res);
      }
    });
  });
}

Obviously the use cases don’t stop there. It would be possible to connect a network of applications to each other and distribute data across them all without having to worry about different platforms and API’s. Just simply decide which collections you want to openly share and allow other apps, wherever or whatever they might be, to subscribe to them.

About 

I run a small web development agency in Salisbury, UK. We provide both front-end/back end solutions and infrastructure management. My specific role is to identify the needs of our clients and providing an online solution that is easy to administer, secure, scalable and maintainable.

 

My agency website is white-fire.co.uk. Contact us if you need a consultant.

Published inJavaScriptMeteor.JS

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *