TeNNoX
TeNNoX

Reputation: 2073

How to wait observer call after Mongo insert on Meteor Server

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.

Upvotes: 1

Views: 118

Answers (1)

Harry Adel
Harry Adel

Reputation: 1446

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

Upvotes: -1

Related Questions