unhandledRejection MongoServerError: Transaction with { txnNumber: 4 } has been committed

I have an express endpoint that updates a user entity - just putting some data into its document.
The update is done using transaction with a session.
It works - if I abort, the user entity remains without any change - and if I commit the change applies.

However there some weird issues with that. Because if I do the same operation, or just any other HTTP requests to the backend api - even requests that sent to another endpoints - over and over again, then I try the same operation of updating the same user entity, and I got this error:

unhandledRejection MongoServerError: Transaction with { txnNumber: 4 } has been committed.

I have read the docs carefully and there is not a single place stating how to work with the sessions.

  1. Should I create one session for the whole mongo client to be reused for every transaction, and just when gracefully shutting down the node process, should I also end the session? (just before doing client.close() )?

  2. Should I create a new session for every transaction (on the same mongo client), and just after either commit or abort to also end the session?

I have tried both to solve the issue I have with these but both of them yield the same results.

Also, a general question: should I interact with the database 100% with transactions? is it a good or bad practice?

Hey @Raz_Buchnik,

Welcome to the MongoDB Community :sparkles:

It is advisable to minimize the use of transactions in your workflow by ensuring that your schema is designed to primarily target a single document with each update, approximately 99.9% of the time. Transactions should be used less and should be very much reserved for exceptional cases or edge-case scenarios.

You can reuse a session for multiple transactions. Please refer to the Transactions and Sessions documentation to read more.

It is recommended to minimize the use of transactions to avoid increased contention. Typically, you should do less operation (< 1%) using transactions.

I hope it helps. Please let us know if you have any further questions related to the above information.

Best regards,