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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With