Skip to content

Commit

Permalink
docs(transactions): add example of aborting a transaction
Browse files Browse the repository at this point in the history
Fix #7113
  • Loading branch information
vkarpov15 committed Nov 2, 2018
1 parent d245847 commit d10274e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
15 changes: 15 additions & 0 deletions docs/transactions.jade
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ block content
[require:transactions.*basic example]
```

## Aborting a Transaction

The most important feature of transactions is the ability to roll back _all_
operations in the transaction using the [`abortTransaction()` function](https://docs.mongodb.com/manual/reference/method/Session.abortTransaction/).

Think about [modeling a bank account in Mongoose](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html#transactions-with-mongoose).
To transfer money from account `A` to account `B`, you would decrement
`A`'s balance and increment `B`'s balance. However, if `A` only has a balance
of $5 and you try to transfer $10, you want to abort the transaction and undo
incrementing `B`'s balance.

```javascript
[require:transactions.*abort]
```

## With Mongoose Documents and `save()`

If you get a [Mongoose document](/docs/documents.html) from [`findOne()`](/docs/api.html#findone_findOne)
Expand Down
18 changes: 18 additions & 0 deletions test/docs/transactions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,24 @@ describe('transactions', function() {
then(doc => assert.ok(doc));
});

it('abort', function() {
// acquit:ignore:start
const Customer = db.model('Customer0', new Schema({ name: String }));
// acquit:ignore:end
let session = null;
return Customer.createCollection().
then(() => Customer.startSession()).
then(_session => {
session = _session;
session.startTransaction();
return Customer.create([{ name: 'Test' }], { session: session });
}).
then(() => Customer.create([{ name: 'Test2' }], { session: session })).
then(() => session.abortTransaction()).
then(() => Customer.countDocuments()).
then(count => assert.strictEqual(count, 0));
});

it('save', function() {
const User = db.model('User', new Schema({ name: String }));

Expand Down

0 comments on commit d10274e

Please sign in to comment.