Two collection updates: Ensure that both or neither are executed


(This is theoretical! An obvious solution would be to store the information in one document.)

Project: Users have credits, with which they can purchase special items.

When the user clicks on the purchase button, a method is executed, where two things need to happen:

  1. decrease users credit amount, by the price of the item
  2. push the item id into an array inside the user document (contains id’s of all items the user purchased)


UserData.update({_id: this.userId}, {$inc: {credit: price}});
UserInfo.update({_id: this.userId}, {$push: {'purchased.items': {_id: source._id, time:}}});

My problem now is, how do I ensure that either both updates are executed or none?

I know about try { } catch { }
but this would only work for one update right?


What you want is a transaction and the closest you can get to that with mongodb is a two-phase commit strategy.

Check this out:


I’m too slow, just what I was going to link!