![]() |
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.jsFirst, make sure you have the mongodb package installed. You can install it using npm: npm install mongodb Step 1: Connect to MongoDBCreate 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 SessionStart a session to use for the transaction. const session = client.startSession();
session.startTransaction(); Step 3: Perform Operations in the TransactionUse 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
await session.commitTransaction(); If there is an error. await session.abortTransaction(); Step 5: End the SessionEnd the session after committing or aborting the transaction. session.endSession(); Step 6: Close the MongoDB ClientClose the MongoDB client to clean up resources. await client.close(); Example: Here is an example of using MongoDB transactions in a Node.js application.
Output: Run “ node mongots.js ” to see output in terminal. Database Stores it: ![]() snapshot of mongoDBcompass Note: It is crucial to handle errors appropriately by catching exceptions and ensuring the transaction is aborted if any operation fails. |
Reffered: https://www.geeksforgeeks.org
Node.js |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |