Callback whenever subscription receives data, but before local collection is updated


#1

Does anyone know what the best approach is to run a callback whenever a subscription on a client receives data, whether it’s update or insert or delete, but before the local collection is updated. Say clients insert document A then B then C, on the server when it receives B it decides to merge B with A and delete B so they’re consolidated into a single document. On the client I want to run a callback whenever A and B and C were inserted, but also when A was updated by being merged with B (and subsequently B was deleted). I need to run a bit of code when the subscription data is received on the client but before the local collection is updated.


#2

I found it buried in the docs, figured I’d leave it here in case it helps anyone else. Collection cursors have .observe() and .observeChanges() callbacks.

http://docs.meteor.com/#/full/observe
http://docs.meteor.com/#/full/observe_changes

So you can subscribe and react to changes in queries like this

let postsCursor = Posts.find({}, {sort: {timestamp : 1}, limit:20 });
postsCursor.observe({
  added: function(doc) {
    //
  },
  changed: function(newDoc,oldDoc) {
    //
  },
  removed: function(oldDoc) {
    //
  },
  movedTo: function(doc,fromIndex,toIndex,beforeDocId){
   //
  }
});

#3

And you can use observe together with a local-only collection where you mirror/consolidate the original client/server collection.