Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor DDP: How to get notified when a NEW document is added to a Collection

I am writing a piece of software that connects to a Meteor server via DDP to read data.

The problem I am facing is figuring out how to differentiate between a NEW document getting added to a collection and getting notified about already-existing documents.

When I first connect to the server, I get a series of added messages to populate the clientside collection. I don't know how to differentiate between those messages, and the ones that come later, indicating a new document was added live. This gets even worse when the DDP client needs to reconnect to the server, at which point all of the current documents are again sent as added messages.

like image 875
Allie the Icon Avatar asked Jul 30 '14 19:07

Allie the Icon


1 Answers

Took me a while to actually realise, but this is exactly the kind of thing that the low-level publish API is designed for. Read the section from "Alternatively, a publish function can..." downwards, and it should be pretty clear how you only send added messages for genuinely new documents. Or to provide a simple example:

Both server and client:

MyData = new Meteor.Collection("mydata");

Client:

Meteor.subscribe('myPub', myFilter);

Server:

Meteor.publish('myPub', function(filter) {
  var self = this;
  var initializing = true;

  var handle = MyData.find(filter).observeChanges({
    added: function (id, fields) {
      if (!initializing)
        self.added("mydata", id, fields);
    },
    changed: function(id, fields) {
      self.changed("mydata", id, fields);
    },
    removed: function (id) {
      self.removed("mydata", id);
    }
  });
  initializing = false;
  self.ready();

  self.onStop(function () {
    handle.stop();  // v. important to stop the observer when the subscription is stopped to avoid it running forever!
  });
});

UPDATE

This is so fundamental I've actually written a blog post about it.

like image 141
richsilv Avatar answered Sep 28 '22 06:09

richsilv