Combining database accesses into a transaction

I have an application that predates the transaction api written in Node.js. We have created classes that loosely correspond to database collections. Each class will get its own connection to the database to update the documents. Now, we want to combine several of these updates into a transaction. Do all of the database updates have to be on the same connection (client) to the database as the session for the transaction to work properly?

Hi @William_Odefey, and welcome!

Transactions are associated with a single session instance. See also MongoDB Transactions.
So you won’t be able to use different client (MongoClient) as a session is started from a single client. i.e.

const client = new MongoClient(uri);
await client.connect();
const session = client.startSession();

...

const coll1 = client.db('mydb1').collection('foo');
const coll2 = client.db('mydb2').collection('bar');

await coll1.insertOne({ abc: 1 }, { session });
await coll2.insertOne({ xyz: 999 }, { session });

Generally you should use a single MongoClient instance for your application lifetime. Each class can have their own collection instance and use a connection from the connection pool, but they should use the same client (as shown on the example above). For example, you could pass the client into a class on construction to share the same client.

Regards,
Wan.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.