डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

Full Stack Web Development with Laravel

Full Stack Web Development with Laravel

Affiliate Program

Affiliate Program

Transactions and rollback in mongodb with an example

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';
const client = new MongoClient(url, { useUnifiedTopology: true });

// Connect to MongoDB
client.connect(function(err) {
  if (err) throw err;

  const db = client.db(dbName);
  const collection1 = db.collection('collection1');
  const collection2 = db.collection('collection2');

  const session = client.startSession();

  // Start a transaction
  session.startTransaction();

  try {
    // Perform multiple operations as a single transaction
    collection1.insertOne({ name: 'John' }, { session });
    collection2.insertOne({ name: 'Jane' }, { session });

    // Commit the transaction
    session.commitTransaction(function(err) {
      if (err) throw err;
      console.log('Transaction committed successfully.');
      client.close();
    });
  } catch (error) {
    // Roll back the transaction if any operation fails
    session.abortTransaction(function(err) {
      if (err) throw err;
      console.log('Transaction aborted.');
      client.close();
    });
  }
});
© 2016 - 2023, All Rights are Reserved.