title: Cannot call abortTransaction after calling commitTransaction: error in nodejs application
body: <p>I am having an issue with mongodb driver that I am not able to understand.</p>
  <p>Some context. I am creating an NFT collection ranker endpoint. To that end I am attempting to store processed data in two separate collections <code>rankings</code> and <code>sortedRankings</code>. <code>rankings</code> contains collection level data and <code>sortedRankings</code> contains the sorted collection.</p>
  <p>I found out about mongodb transactions and decided to give it a shot. Here is the associated code in question.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>export async function rankingInsertOrUpdate(
    storedAccuracy: WithId &lt; NFTCollectionRanking &gt; | null,
    rankingDocument: NFTCollectionRanking,
    sortedRankingDocument: NFTSortedRanking
  ) {
    const session = client.startSession();
  
    try {
      if (storedAccuracy === null) {
        runTransationWithRetry(insertRankings, session);
      } else if (rankingDocument.accuracy &gt; storedAccuracy.accuracy) {
        runTransationWithRetry(updateRankings, session);
      }
    } catch (error: any) {
      throw new Error(error);
    } finally {
      session.endSession();
    }
  
    async function insertRankings() {
      session.startTransaction({
        readConcern: {
          level: 'snapshot'
        },
        writeConcern: {
          w: 'majority'
        },
      });
  
      try {
        await rankings.insertOne(rankingDocument);
        await sortedRankings.insertOne(sortedRankingDocument);
      } catch (error) {
        console.log('Caught exception during insert transaction, aborting.');
        session.abortTransaction();
        throw error;
      }
  
      commitWithRetry(session);
    }
  
    async function updateRankings() {
      session.startTransaction({
        readConcern: {
          level: 'snapshot'
        },
        writeConcern: {
          w: 'majority'
        },
      });
  
      try {
        await rankings.updateOne(rankingDocument);
        await sortedRankings.updateOne(sortedRankingDocument);
      } catch (error) {
        console.log('Caught exception during update transaction, aborting.');
        session.abortTransaction();
        throw error;
      }
  
      commitWithRetry(session);
    }
  }
  
  function runTransationWithRetry(txnFunc: any, session: any) {
    while (true) {
      try {
        txnFunc(session); // performs transaction
        break;
      } catch (error: any) {
        // If transient errorm retry the whole function
        if (
          error.hasOwnProperty('errorLabels') &amp;&amp;
          error.errorLabels.includes('TransientTransactionError')
        ) {
          console.log('TransientTransactionError, retrying transaction ...');
          continue;
        } else {
          throw error;
        }
      }
    }
  }
  
  function commitWithRetry(session: ClientSession) {
    while (true) {
      try {
        session.commitTransaction(); // Uses write concern set at transaction start
        console.log('Transaction committed');
        break;
      } catch (error: any) {
        // Can retry commit
        if (
          error.hasOwnProperty('errorLabels') &amp;&amp;
          error.errorLabels.includes('UnknownTransactionCommitResult')
        ) {
          console.log(
            'UnknownTransactionCommitResult, retrying commit operation ...'
          );
          continue;
        } else {
          console.log('Error during commit ...');
          throw error;
        }
      }
    }
  }</code></pre>
  </div>
  </div>
  </p>
  <p>Whats happening specifically is that node is crashing at the very last second. Here is a pic of the console logs.</p>
  <p><a href="https://i.stack.imgur.com/UYG2P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UYG2P.png" alt="enter image description here" /></a></p>
  <p>I run the POST, let it process everything, then it crashes. The processed data appears in my DB. So it is successful in sending it to the DB, but I'm not able to find out why abortTransaction is being called. If an error was thrown during the <code>insertRankings</code> or <code>updateRankings</code> function, then it would've console logged <code>Caught exception during insert transaction, aborting</code>, but this is not appearing in my terminal. The only statement printed is <code>Transaction committed</code>. The session is also ended with <code>session.endSession()</code> after <code>runTransactionWithRetry</code> is finished. Not sure how it's successful but crashes at the end.</p>
  <p>I used the retry flow from the mongo docs found here <a href="https://www.mongodb.com/docs/manual/reference/method/Session.startTransaction/" rel="nofollow noreferrer">https://www.mongodb.com/docs/manual/reference/method/Session.startTransaction/</a> . I tried following it a T. I have checked other posts like <a href="https://stackoverflow.com/questions/52090819/mongodb-do-i-need-a-aborttransaction-after-committransaction-that-fails">mongodb do I need a abortTransaction after commitTransaction that fails?</a> and <a href="https://stackoverflow.com/questions/65894050/mongoerror-cannot-call-aborttransaction-twice-mongoerror-cannot-call-aborttra">MongoError: Cannot call abortTransaction twice; MongoError: Cannot call abortTransaction after calling commitTransaction</a> but they do not help answer my question.</p>
  <p>I'm kinda stumped and any help would be amazing.</p>