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() } }
);
}
});