Search code examples
node.jsmongodbtransactionsrollback

Transaction mongodb


I need to write into two different mongodb collections using an 'all or nothing' process. Fyi I use NodeJs in my backend side.

As far as I know MongoDb provides atomicity when it comes to a single collection, but it does not when we need to write into multiple collections.

So I'd like to know a way of emulating this a transaction in nodejs/mongodb in order to avoid writing into one collection if the other failed and also getting the possibility of doing a 'roll back' if the second process fails.

Thank you guys!


Solution

  • In MongoDB (prior to 4.0) there is no way you can fully implement transactions on database level. However, there are some mechanisms which provides some transactions functionality. You can read about them in documentation.

    Since MongoDB 4.0, transactions are supported. Very little chage is needed in your current code to support them. There's a new section in the documentation fully dedicated to the subject