Home Wait for mongo writes before returning from a find
Reply: 0

Wait for mongo writes before returning from a find

user1378
1#
user1378 Published in April 19, 2018, 8:48 pm

I want a store js object that manages a mongodb collection and behaves like that:

store.insert(thing); // called from a pubsub system that don't wait the insert to finish

store.get(); // returns a promise that resolves to the things in the collection
// even if called immediately after insert it must contain the last thing inserted

I implemented it manually like that:

let inserts = 0;
let afterInserts = [];

const checkInsertsFinished = () => {
  if (inserts === 0) {
    afterInserts.forEach(resolve => resolve());
    afterInserts = [];
  }
};

const decrementInserts = () => {
  inserts -= 1;
  checkInsertsFinished();
};

const insertsFinished = () =>
  new Promise((resolve) => {
    afterInserts.push(resolve);
    checkInsertsFinished();
  });

const insert = (thing) => {
  inserts += 1;
  db.collection('mycollection').insertOne(thing).then(decrementInserts);
};

const get = async () => {
  await insertsFinished(); // if there are inserts happening, wait for them to finish
  return db.collection('mycollection').find({}).toArray();
};

return { insert, get };

I suppose that there are more standard ways to accomplish this but I miss the vocabulary to find libs or built-in features... How would you do that?

Thanks for your advices.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301142 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO