Meteor DDP: how to get notified when a new document is added to the collection

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

The problem I am facing is determining how to distinguish between a new document being added to the collection and receiving notifications of existing documents.

When I first connect to the server, I get a series of added messages to populate the client collection. I do not know how to distinguish between these messages, and those that appear later, indicating that a new document has been added live. This gets even worse when the DDP client needs to reconnect to the server, after which all current documents are sent again as added messages.

+6
source share
2 answers

It took a while to actually understand, but this is exactly what is intended for the low-level publishing API . Read the section โ€œAlternatively, the publish function may ...โ€ down, and it should be pretty clear how you send only added messages for truly new documents. Or provide a simple example:

Both server and client:

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

Customer:

 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 that I actually wrote a blog post about it.

+10
source

I had this problem in the past and found a solution. Set the variable during the first rendering and change the variable after the main observation - example:

 var initializing = true; var handle = Collection.find().observe({ added: function (item) { if (!initializing) // do stuff with newly added items, this check skips the first run } }); initializing = false; 
+3
source

Source: https://habr.com/ru/post/973127/


All Articles