I have a situation of unexpected, and inconsistent Mongo collection docs events firing.
To simplify, it goes like this:
Collection A: Bookings.
Collection B: Invoices.
Each Booking can have zero or one invoices, and is referenced by an optional attribute ‘invoiceID’ on the Booking doc.
Invoices are created and manipulated by a handler that listens to the 3 events fired by the Bookings Mini Mongo collection:
Bookings.observe({
added: this._onBookingsAdded,
changed: this._onBookingChanged,
removed: this._onBookingRemoved,
});
So when a Booking is added, the Bookings collection fires ‘added’, and the Invoice handler listens and creates a new Invoice. Then, still in the ‘added’ callback, it updates MiniMongo’s Bookings collection. It updates the newly added Booking doc with the matching invoiceID by calling:
_onBookingsAdded = newBooking => {
const newInvoiceID = Invoices.insert(new InvoiceOM({...}));
Bookings.update(
{ _id: newBooking._id },
{ $set: { invoiceID: newInvoiceID } },
);
};
Then I get a ‘changed’ event for that same Booking doc, with the only change of having an ‘invoiceID’ set to it.
Just as expected.
So essentially, I am updating the MiniMongo’s new doc while the ‘added’ event has not yet finished.
Now comes the weird part -
One of 2 options of unexpected behaviors happen, and it seems quite random which one of the 2 (I distinguish them from debugging, and it seems that each booking triggers one of the 2):
- After updating the invoiceID on the new Booking, a second passes, and I get a ‘removed’ event for that same booking, followed by an ‘added’ event for the same booking again.
- After updating the invoiceID on the new Booking, I get another ‘changed’ event for that Booking, only this time the change is reverting the invoiceID from what it was set, back to undefined again.
Any ideas why? How can I have a reliable chain of events, and have the invoiceID updated only once?
I know that Meteor Collection Hooks might solve this, but I want to understand it first.