How to Use MongoDB Transactions in Node.js?
Last Updated :
27 Jun, 2024
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
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.
JavaScript
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:
snapshot of mongoDBcompassNote: It is crucial to handle errors appropriately by catching exceptions and ensuring the transaction is aborted if any operation fails.
Similar Reads
How to Use Transactions in MySQL with NodeJS? Transactions in MySQL are used to execute a series of operations as a single unit of work, ensuring that all operations either succeed or fail together. This is crucial in maintaining data integrity, especially when dealing with complex operations that involve multiple database queries. In Node.js,
2 min read
Using Transactions in MongoDB MongoDB is originally designed as a NoSQL database which has evolved significantly to support more complex operations, including transactions. Since version 4.0, MongoDB supports multi-document transactions and allows developers to perform operations across multiple documents and even multiple colle
7 min read
Transactions in Mongoose In modern web applications, maintaining data integrity across multiple database operations is crucial. Transactions in Mongoose allow developers to execute multiple database operations within a single transaction, ensuring that all operations are successful, or none are executed. This guarantees con
6 min read
How to replace one document in MongoDB using Node.js ? MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Inst
1 min read
Multi-Document Transaction in MongoDB MongoDB is a NoSQL database known for its flexible schema and high performance. While traditional relational databases offer ACID (Atomicity, Consistency, Isolation, Durability) transactions across multiple tables, NoSQL databases like MongoDB initially lacked this feature. However, since MongoDB 4.
3 min read