16

I have two applications that I need to synchronise. One of them will receive data from users and the other will display the data. Both applications will work on different servers. They could be disconnected at some times and they need to continue working until reconnect, so I will replicate the data from the first application on the second application.

On Meteor documentation I found DDP.connect(url)but I'm not sure how to use it. I found many questions and examples connecting non Meteor applications with Meteor using DDP, but nothing about connecting two Meteor applications.

My first approach was something like this:

Application 1

Items = new Meteor.Collection('items');
Items.insert({name: 'item 1'});
if (Meteor.isServer) {
  Meteor.publish('items', function() {
    return Items.find();
  });
}

Application 2

Items = new Meteor.Collection('items')
if (Meteor.isServer) {
  var remote = DDP.connect('http://server1.com/);
  remote.onReconnect = function() {
    remote.subscribe('items');
    var items = Items.find();
    console.log(items.count());  // expected to be 1 but get 0
  } 
}

On the second application, how can I get the items from the first application?

Camilo
  • 2,844
  • 2
  • 29
  • 44

1 Answers1

34

I got a clue from this question How to properly use Meteor.connect() to connect with another Meteor server. I missed it because it was about the old Meteor.connect() that changed to DDP.connect().

This worked on client and server

var remote = DDP.connect('http://server1.com/');
Items = new Meteor.Collection('items', remote); 

remote.subscribe('items', function() {
  var items = Items.find();
  console.log(items.count());  // get 1         
});

Now I can watch for changes in application 1 from application 2 using Items.find().observe()

Warning

There is a bug on Meteor that will stop the connection between applications:

Update

The bug was solved

Update 2

This is a sample project tested with Meteor 0.6.6.2 https://github.com/camilosw/ddp-servers-test

Community
  • 1
  • 1
Camilo
  • 2,844
  • 2
  • 29
  • 44
  • 2
    The issue (1543) appears to be fixed now. (Meteor >0.8.3) – markmarijnissen Oct 30 '14 at 23:30
  • @Camilo Is the code above on the client side or server side? – Haikal Nashuha May 12 '15 at 12:51
  • @Haikal Nashuha It work on both sides. You can see an example here working on server side [https://github.com/camilosw/ddp-servers-test](https://github.com/camilosw/ddp-servers-test) – Camilo May 12 '15 at 15:18
  • why is this necessary? can't he provide external mongo source? MONGO_URL=mongodb://anotherserver:8000/db_name Just want to know what is best practice. – SO is full of Monkeys Nov 19 '15 at 14:12
  • 3
    @user1623481 there are cases when you only want to expose a subset of data to another app instead of expose the whole database. – Camilo Nov 19 '15 at 16:16
  • This answer absolutely saved me! There's practically nothing around on how you go about doing this. – icc97 Mar 15 '17 at 08:07