Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor observe changes added callback on server fires on all item

Tracker.autorun(function() {
  DATA.find().observeChanges({
    added: function(id, doc) {
       console.log(doc);
    }
  });
});

This code is being called on the server. Every time the meteor server starts, the added function fires for every single item in the database. Is there a way to have the added callback fire only when new items are added?

like image 940
Bads Avatar asked Jan 25 '14 20:01

Bads


1 Answers

added will be called for every document in the result set when observeChanges is first run. The trick is to ignore the callback during this initialization period. I have an expanded example in my answer to this question, but this code should work for you:

(function() {
  var initializing = true;
  DATA.find().observeChanges({
    added: function(id, doc) {
      if (!initializing) {
        console.log(doc);
      }
    }
  });
  initializing = false;
})();

Note that Tracker.autorun is a client-only function. On the server I think it only ever executes once.

like image 195
David Weldon Avatar answered Oct 14 '22 20:10

David Weldon