NodeJS MongoDb Transactions


From MongoDB 4.0 they introduced transactions called 'Multi-Document transactions'.

Install MongoDB

Run below commands to install MongoDB cluster in 3 different ports by default in 27017, 27018, 27019

npm i run-rs -g
run-rs --version 4.0.0
Purging database...
Running '/home/node/lib/node_modules/run-rs/4.0.0/mongod'
Starting replica set...
Started replica set on "mongodb://localhost:27017,localhost:27018,localhost:27019"
Connected to oplog

Install node js Mondb client driver

npm install mongodb

NodeJS MongoDB Transaction Example

  1. Start a client session using startSession() from client.
  2. Use withTransaction() to start a transaction.
  3. Write logic in withTransaction() callback function
  4. Must pass the session object to the write operations.
// Boilerplate: connect to DB
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
await client.connect();


const session = client.startSession({defaultTransactionOptions: {
   readConcern: { level: 'local' },
   writeConcern: { w: 'majority' },
   readPreference: 'primary'
}});


await session.withTransaction(async function() {
     const coll1 = client.db('mydb1').collection('users');
     const coll2 = client.db('mydb2').collection('roles');

     await coll1.insertOne({ 'userName': "Foo" }, { session });

     await coll2.insertOne({ 'roleName':"Admin" }, { session });
  });