Combining database accesses into a transaction

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