|
1 | 1 | # Transactions in Mongoose
|
2 | 2 |
|
3 |
| -[Transactions](https://www.mongodb.com/transactions) are new in MongoDB |
4 |
| -4.0 and Mongoose 5.2.0. Transactions let you execute multiple operations |
5 |
| -in isolation and potentially undo all the operations if one of them fails. |
| 3 | +[Transactions](https://www.mongodb.com/transactions) let you execute multiple operations in isolation and potentially undo all the operations if one of them fails. |
6 | 4 | This guide will get you started using transactions with Mongoose.
|
7 | 5 |
|
8 | 6 | <h2 id="getting-started-with-transactions"><a href="#getting-started-with-transactions">Getting Started with Transactions</a></h2>
|
@@ -86,6 +84,33 @@ Below is an example of executing an aggregation within a transaction.
|
86 | 84 | [require:transactions.*aggregate]
|
87 | 85 | ```
|
88 | 86 |
|
| 87 | +<h2 id="asynclocalstorage"><a href="#asynclocalstorage">Using AsyncLocalStorage</a></h2> |
| 88 | + |
| 89 | +One major pain point with transactions in Mongoose is that you need to remember to set the `session` option on every operation. |
| 90 | +If you don't, your operation will execute outside of the transaction. |
| 91 | +Mongoose 8.4 is able to set the `session` operation on all operations within a `Connection.prototype.transaction()` executor function using Node's [AsyncLocalStorage API](https://nodejs.org/api/async_context.html#class-asynclocalstorage). |
| 92 | +Set the `transactionAsyncLocalStorage` option using `mongoose.set('transactionAsyncLocalStorage', true)` to enable this feature. |
| 93 | + |
| 94 | +```javascript |
| 95 | +mongoose.set('transactionAsyncLocalStorage', true); |
| 96 | + |
| 97 | +const Test = mongoose.model('Test', mongoose.Schema({ name: String })); |
| 98 | + |
| 99 | +const doc = new Test({ name: 'test' }); |
| 100 | + |
| 101 | +// Save a new doc in a transaction that aborts |
| 102 | +await connection.transaction(async() => { |
| 103 | + await doc.save(); // Notice no session here |
| 104 | + throw new Error('Oops'); |
| 105 | +}).catch(() => {}); |
| 106 | + |
| 107 | +// false, `save()` was rolled back |
| 108 | +await Test.exists({ _id: doc._id }); |
| 109 | +``` |
| 110 | + |
| 111 | +With `transactionAsyncLocalStorage`, you no longer need to pass sessions to every operation. |
| 112 | +Mongoose will add the session by default under the hood. |
| 113 | + |
89 | 114 | <h2 id="advanced-usage"><a href="#advanced-usage">Advanced Usage</a></h2>
|
90 | 115 |
|
91 | 116 | Advanced users who want more fine-grained control over when they commit or abort transactions
|
|
0 commit comments