How to wait observer call after Mongo insert on Meteor Server

113 Views Asked by At

I figured, when I insert into Mongo, Meteor's Fiber magic waits/blocks until the db acknowledged the write, but not until the observers are called. Is there a way to wait for them?

I'm inserting data in server code, and I have a Caching layer that observes added events on the Collection and casts ObjectModel instances from them:

class CachingService {
  attachObservers() {
    this.collection.observe({
      added: models => this.added(models)
    })
  }
}
const id = Placements.insert({...})
console.log(`Inserted ${id} -`, CachingServices.Placements.getByID(id), Placements.getByID(id, false))

would print:

Inserted ... - undefined, {...}

i.e. the CachingService didn't receive the insert yet, but the database did.

1

There are 1 best solutions below

1
Harry Adel On

Maybe try injecting the observe property on the collection cursor not the instance (i.e testCollection.find().observe ).


Meteor.startup(() => {

  const testCollection = new Mongo.Collection("testCollection");

  testCollection.find().observe({
  added: function(document) {
    console.log("groups observe added value function");
    console.log(document);
  }
});

  testCollection.insert({ foo: 'bar' });
})

Other helpful questions: Meteor collection observe changes rightly cursor.observe({added}) behavior in Meteor