Connection.prototype.transaction()

Parameters
  • fn «Function» Function to execute in a transaction

  • [options] «mongodb.TransactionOptions» Optional settings for the transaction

Returns:
  • «Promise<Any>» promise that resolves to the returned value of fn

Requires MongoDB >= 3.6.0. Executes the wrapped async function in a transaction. Mongoose will commit the transaction if the async function executes successfully and attempt to retry if there was a retriable error.

Calls the MongoDB driver’s session.withTransaction(), but also handles resetting Mongoose document state as shown below.

Example:

  1. const doc = new Person({ name: 'Will Riker' });
  2. await db.transaction(async function setRank(session) {
  3. doc.rank = 'Captain';
  4. await doc.save({ session });
  5. doc.isNew; // false
  6. // Throw an error to abort the transaction
  7. throw new Error('Oops!');
  8. },{ readPreference: 'primary' }).catch(() => {});
  9. // true, `transaction()` reset the document's state because the
  10. // transaction was aborted.
  11. doc.isNew;