Home > Enterprise >  Do I really have to pass the session as a param when doing Mongo Node transaction
Do I really have to pass the session as a param when doing Mongo Node transaction

Time:10-18

When doing a transaction like

await ( await this.client )
 .withSession(async (session) => {
    try {
      session.startTransaction();
      await collection1.updateMany({ id }, { $set: { done: true } }, { session });
      await collection2.updateMany({ someId, test: { $exists: true } }, { $set: { test: [] } }, { session });
      session.commitTransaction();
    } catch (err) {
      session.abortTransaction();
      throw new Error(`Failed`);
    }
 });

Why do I have to pass the { session } as a param for the 2 updates?

The documentation doesn't seem to explain why that is, shouldn't everything between a start, stop session use that session, including await.collection1?

Thank you

CodePudding user response:

This is totally normal in all the DBMS that i worked with.
As far as i know, the reason behind that is that you dont always want to add every DB-transaction to the started Transaction, because it might lead to reduced throughput and blocking.

So you only want to add Transactions that change the state of a Document and which are essential. E.g. most of the time you dont want to add simple read operations to the transactions and block the document with that

  • Related