DEV Community

kishor sutradhar
kishor sutradhar

Posted on

Today’s new knowledge #9 (Understanding Transaction Rollbacks in Mongoose)

Today’s Overview:

Hola, everyone! I hope you're all doing great. It's been a while since I last wrote a blog post. I've been working on a full-stack project for my resume, and since I'm the only one developing it, it is taking some time to complete the project. After completing the project I want some feedback from you guys. ok enough about me, I learned some new concepts about MongoDB and Mongoose. Here is one I find quite useful for any project which is Transaction Rollbacks. So let's dive into it.

Table of contents

Transactions and Rollbacks

A transaction rollback is a powerful mechanism that helps you maintain consistency especially when multiple operations need to either be fully completed or entirely undone.
A transaction in MongoDB is a way to group multiple operations together into a single unit. All operations within a transaction are treated as if they happen at once.
If any operation in the transaction fails, MongoDB will automatically rollback the entire transaction to its initial state, undoing all changes made.

Why Use Transaction Rollbacks?

  1. Single unit: Transactions allow you to bundle several operations into a single unit.
  2. Prevent Data Corruption: When the operation fails rollback prevents data corruption.
  3. Maintain consistency As multiple operations must work together or roll back if fail to perform the operation it helps to maintain consistency.
  4. Error Handling: In the case of unexpected errors or failures, transaction rollbacks provide a safety net by reversing any changes made during the transaction.
  5. Simplify Complex Operations: When working with multiple collections or documents, rollbacks provide a simple way to handle complex operations

What to consider when using Transaction Rollbacks?

While transaction rollbacks are a powerful tool for maintaining data integrity, there are several factors to consider when using them:

  1. Performance: Transactions come with some performance overhead due to the need to track changes and ensure atomicity. Use them judiciously in performance-sensitive applications.
  2. Transaction Limits: MongoDB has certain limits on the size of transactions, such as the maximum number of operations or document size. Be mindful of these limits when dealing with large or complex transactions.

Steps to Implement a Transactions and Rollback in Mongoose

  1. Create a mongoose sassion const session = await mongoose.startSession();
  2. Start a transaction await session.startTransaction();
  3. Perform the operations
  4. Commit the transaction await session.commitTransaction();
  5. Close the session session.endSession();
  6. In case of error and rollback the transaction await session.abortTransaction();

Example

Here's an example using Mongoose:


async function performTransaction() {

  //create a session and start transaction
  const session = await mongoose.startSession();
  session.startTransaction();

  try {
    //  operations within the transaction
    const user = await User.findOneAndUpdate(
      { _id: "userId1" },
      { $set: { name: "John Doe" } },
       //have to specify the session in the options field
      { new: true, session }
    );

    if (!user) {
      throw new Error("User not found");
    }

    const order = await Order.create(
      [
        {
          userId: user._id,
          item: "Laptop",
          status: "Processing",
        },
      ],
      {
        //have to specify the session in the options field
       session 
      }
    );

    // If all operations are successful, commit the transaction
    await session.commitTransaction();

  } catch (error) {
    // If an error occurs, abort the transaction (rollback)
    await session.abortTransaction();
    console.error("Transaction aborted due to error:", error);
  } finally {
   // and finally end the session
    session.endSession();
  }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

I think this is a great feature for every developer to use in their complex write operation. one more thing Transaction rollbacks can not be used in read operations. ok that's all for today.

Top comments (0)