Building a production-ready web app requires you to ensure that its safe and scalable.
Relational databases like MySQL support ACID transactions natively.
But MongoDB is a NoSQL database and doesnt support ACID transactions by default.
As a programmer, you should know how to introduce ACID properties into your MongoDB databases.
What Are Database Transactions?
Database transactions adhere to the concepts of ACID characteristics.
This helps to ensure that no changes occur unless all operations are successful.
It also ensures the database is consistent.
Transactions aren’t supported on standalone MongoDB installations.
Youll need to use aMongoDB replica setorMongoDB sharded clusterfor transactions to work.
Therefore, the easiest way to use transactions is tocreate a cloud-hosted MongoDB instance(MongoDB Atlas).
By default, every Atlas database instance is a replica set or sharded cluster.
If you havent before now, install mongoose by runningnpm install mongoosein your terminal.
Acreatequery that runs in a transaction usually takes in and returns an array.
you’re free to see this in the code above where it createsnewJoband stores its_idproperty in thenewJobIdvariable.
You are free to choose which style to use when implementing database transactions in MongoDB.
This implementation does not use thecommitTransaction()andabortTransaction()functions.
This is because thewithTransaction()function automatically commits successful transactions and aborts failed ones.
The only function that you should call in all cases is thesession.endSession()function.
Implementing ACID Database Transactions in MongoDB
Database transactions are easy to use when done correctly.