deno.land / x / mongoose@6.7.5 / docs / transactions.md
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.
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:
[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]
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]
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 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]
Version Info