How to Use MongoDB Transactions in Node.js?
Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js.
Prerequisites
- MongoDB (Version 4.0 or higher Recommended)
- Replica set
Steps to Use MongoDB Transactions in Node.js
First, make sure you have the mongodb package installed. You can install it using npm:
npm install mongodb
Step 1: Connect to MongoDB
Create a MongoClient instance and connect to your MongoDB server.
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
await client.connect();
Step 2: Start a Session
Start a session to use for the transaction.
const session = client.startSession();
session.startTransaction();
Step 3: Perform Operations in the Transaction
Use the session object to perform multiple operations.
const database = client.db('testdb');
const collection1 = database.collection('collection1');
const collection2 = database.collection('collection2');
try {
await collection1.insertOne({ name: "Alice" }, { session });
await collection2.insertOne({ name: "Bob" }, { session });
await session.commitTransaction();
console.log('Transaction committed.');
} catch (error) {
await session.abortTransaction();
console.error('Transaction aborted due to an error:', error);
} finally {
session.endSession();
}
Step 4: Commit or Abort the Transaction
- If all operations succeed, commit the transaction.
- If any operation fails, abort the transaction.
await session.commitTransaction();
If there is an error.
await session.abortTransaction();
Step 5: End the Session
End the session after committing or aborting the transaction.
session.endSession();
Step 6: Close the MongoDB Client
Close the MongoDB client to clean up resources.
await client.close();
Example: Here is an example of using MongoDB transactions in a Node.js application.
const { MongoClient } = require("mongodb");
async function main() {
const uri = "mongodb://localhost:27017";
// Replace with your MongoDB connection string
const client = new MongoClient(uri);
try {
await client.connect();
const session = client.startSession();
session.startTransaction();
const database = client.db("testdb");
const collection1 = database.collection("collection1");
const collection2 = database.collection("collection2");
try {
await collection1.insertOne({ name: "Alice" }, { session });
await collection2.insertOne({ name: "Bob" }, { session });
await session.commitTransaction();
console.log("Transaction committed.");
} catch (error) {
await session.abortTransaction();
console.error("Transaction aborted due to an error:", error);
} finally {
session.endSession();
}
} finally {
await client.close();
}
}
main().catch(console.error);
Output: Run " node mongots.js " to see output in terminal.
Database Stores it:

Note: It is crucial to handle errors appropriately by catching exceptions and ensuring the transaction is aborted if any operation fails.