deno.land / x / mongoose@6.7.5 / docs / transactions.md

transactions.md

Transactions in Mongoose

Transactions are new in MongoDB 4.0 and Mongoose 5.2.0. Transactions let you execute multiple operations in isolation and potentially undo all the operations if one of them fails. This guide will get you started using transactions with Mongoose.

Getting Started with Transactions

If you haven't already, import mongoose:

import mongoose from 'mongoose';

To create a transaction, you first need to create a session using or Mongoose#startSession or Connection#startSession().

// Using Mongoose's default connection
const session = await mongoose.startSession();

// Using custom connection
const db = await mongoose.createConnection(mongodbUri).asPromise();
const session = await db.startSession();

In practice, you should use either the session.withTransaction() helper or Mongoose's Connection#transaction() function to run a transaction. The session.withTransaction() helper handles:

  • Creating a transaction
  • Committing the transaction if it succeeds
  • Aborting the transaction if your operation throws
  • Retrying in the event of a transient transaction error.
[require:transactions.*withTransaction]

For more information on the ClientSession#withTransaction() function, please see the MongoDB Node.js driver docs.

Mongoose's Connection#transaction() function is a wrapper around withTransaction() that integrates Mongoose change tracking with transactions. For example, suppose you save() a document in a transaction that later fails. The changes in that document are not persisted to MongoDB. The Connection#transaction() function informs Mongoose change tracking that the save() was rolled back, and marks all fields that were changed in the transaction as modified.

[require:transactions.*can save document after aborted transaction]

With Mongoose Documents and save()

If you get a Mongoose document from findOne() or find() using a session, the document will keep a reference to the session and use that session for save().

To get/set the session associated with a given document, use doc.$session().

[require:transactions.*save]

With the Aggregation Framework

The Model.aggregate() function also supports transactions. Mongoose aggregations have a session() helper that sets the session option. Below is an example of executing an aggregation within a transaction.

[require:transactions.*aggregate]

Advanced Usage

Advanced users who want more fine-grained control over when they commit or abort transactions can use session.startTransaction() to start a transaction:

[require:transactions.*basic example]

You can also use session.abortTransaction() to abort a transaction:

[require:transactions.*abort]
mongoose

Version Info

Tagged at
a year ago