withTransaction

The more perfect variant of the native driver's withTransaction function.

withTransaction(callback) => Promise

const { withTransaction, getCollection } = require('mongodash');

const createdDocuments = await withTransaction(async (session) => {
  
  const myDocument1 = { value: 1 };
  const myDocument2 = { value: 2 };
  
  const collection = getCollection('myCollection');
  await testCollection.insertOne(myDocument1, { session });
  await testCollection.insertOne(myDocument2, { session });
  
  return [myDocument1, myDocument2];
});
import { withTransaction, getCollection } from 'mongodash';
import { ClientSession } from 'mongodb';


const createdDocuments = await withTransaction(async (session: ClientSession) => {
  
  const collection = getCollection('myCollection');
  
  const myDocument1 = { value: 1 };
  const myDocument2 = { value: 2 };
  
  await testCollection.insertOne(myDocument1, { session });
  await testCollection.insertOne(myDocument2, { session });
  
  return [myDocument1, myDocument2];
});

👍

Benefits over the native driver's withTransaction function:

  • automatically starts a new clientSession
  • automatically ends the clientSession (even on failure)
  • propagates the value returned from the callback

It does all the necessary code described in the official docs automatically.

In case of an exception, the transaction is aborted automatically.