Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Meteor Collection Hooks - How to run the 'after insert' hook only once the previous 'after insert' has finished

Inserts are happening quicker than the after.insert function can process them and what I want to happen after the current document is inserted is dependent on what happened after the previous document was inserted.

I think the short question might be how do I make it synchronous?

FirstCollection.after.insert(function (userId, doc) {

  lastDoc = SecondCollection.findOne({}, { sort: { $natural: -1 } });

  if (!lastDoc) {
    SecondCollection.insert({
      startNumber: doc.txNumber,
      count: 1,
      duration: 264,
      lastTx: doc.txNumber,
      time: Date.now(),
      finishedAt: 0,
    });
    return;
  }

  if (lastDoc.finishedAt !== 0) {
    if (Date.now() - lastDoc.finishedAt < 60000) {
      return;
    }

    SecondCollection.insert({
      startNumber: doc.txNumber,
      count: 1,
      duration: 264,
      last: doc.txNumber,
      time: Date.now(),
      finishedAt: 0,
    });
    return;
  }

  SecondCollection.update(
    { _id: lastDoc._id },
    { $set: { lastTx: doc.txNumber }, $inc: { count: 1 } }
  );

  if (lastDoc.count === lastDoc.duration) {
    SecondCollection.update(
      { _id: lastDoc._id },
      { $set: { finishedAt: Date.now() } }
    );
  }
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!