Transactions in Mongoose

Sponsor #native_company# — #native_desc#

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.

Your First Transaction

MongoDB currently only supports transactions on replica sets, not standalone servers. To run a local replica set for development on macOS, Linux or Windows, use npm to install run-rs globally and run run-rs --version 4.0.0. Run-rs will download MongoDB 4.0.0 for you.

To use transactions with Mongoose, you should use Mongoose >= 5.2.0. To check your current version of Mongoose, run npm list | grep "mongoose" or check the mongoose.version property.

Transactions are built on MongoDB sessions. To start a transaction, you first need to call startSession() and then call the session’s startTransaction() function. To execute an operation in a transaction, you need to pass the session as an option.

  1. const Customer = db.model('Customer', new Schema({ name: String }));
  2. const session = await db.startSession();
  3. session.startTransaction();
  4. // This `create()` is part of the transaction because of the `session`
  5. // option.
  6. await Customer.create([{ name: 'Test' }], { session: session });
  7. // Transactions execute in isolation, so unless you pass a `session`
  8. // to `findOne()` you won't see the document until the transaction
  9. // is committed.
  10. let doc = await Customer.findOne({ name: 'Test' });
  11. assert.ok(!doc);
  12. // This `findOne()` will return the doc, because passing the `session`
  13. // means this `findOne()` will run as part of the transaction.
  14. doc = await Customer.findOne({ name: 'Test' }).session(session);
  15. assert.ok(doc);
  16. // Once the transaction is committed, the write operation becomes
  17. // visible outside of the transaction.
  18. await session.commitTransaction();
  19. doc = await Customer.findOne({ name: 'Test' });
  20. assert.ok(doc);
  21. session.endSession();

In the above example, session is an instance of the MongoDB Node.js driver’s ClientSession class. Please refer to the MongoDB driver docs for more information on what methods session has.

Aborting a Transaction

The most important feature of transactions is the ability to roll back all operations in the transaction using the abortTransaction() function.

Think about modeling a bank account in 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.

  1. const session = await Customer.startSession();
  2. session.startTransaction();
  3. await Customer.create([{ name: 'Test' }], { session: session });
  4. await Customer.create([{ name: 'Test2' }], { session: session });
  5. await session.abortTransaction();
  6. const count = await Customer.countDocuments();
  7. assert.strictEqual(count, 0);
  8. session.endSession();

The withTransaction() Helper

The previous examples explicitly create a transaction and commits it. In practice, you’ll want to use the session.withTransaction() helper instead. 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.
  1. const session = await Customer.startSession();
  2. // The `withTransaction()` function's first parameter is a function
  3. // that returns a promise.
  4. await session.withTransaction(() => {
  5. return Customer.create([{ name: 'Test' }], { session: session })
  6. });
  7. const count = await Customer.countDocuments();
  8. assert.strictEqual(count, 1);
  9. session.endSession();

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

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().

  1. const User = db.model('User', new Schema({ name: String }));
  2. const session = await db.startSession();
  3. session.startTransaction();
  4. await User.create({ name: 'foo' });
  5. const user = await User.findOne({ name: 'foo' }).session(session);
  6. // Getter/setter for the session associated with this document.
  7. assert.ok(user.$session());
  8. user.name = 'bar';
  9. // By default, `save()` uses the associated session
  10. await user.save();
  11. // Won't find the doc because `save()` is part of an uncommitted transaction
  12. let doc = await User.findOne({ name: 'bar' });
  13. assert.ok(!doc);
  14. await session.commitTransaction();
  15. session.endSession();
  16. doc = await User.findOne({ name: 'bar' });
  17. assert.ok(doc);

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.

  1. const Event = db.model('Event', new Schema({ createdAt: Date }), 'Event');
  2. const session = await db.startSession();
  3. session.startTransaction();
  4. await Event.insertMany([
  5. { createdAt: new Date('2018-06-01') },
  6. { createdAt: new Date('2018-06-02') },
  7. { createdAt: new Date('2017-06-01') },
  8. { createdAt: new Date('2017-05-31') }
  9. ], { session: session });
  10. const res = await Event.aggregate([
  11. {
  12. $group: {
  13. _id: {
  14. month: { $month: '$createdAt' },
  15. year: { $year: '$createdAt' }
  16. },
  17. count: { $sum: 1 }
  18. }
  19. },
  20. { $sort: { count: -1, '_id.year': -1, '_id.month': -1 } }
  21. ]).session(session);
  22. assert.deepEqual(res, [
  23. { _id: { month: 6, year: 2018 }, count: 2 },
  24. { _id: { month: 6, year: 2017 }, count: 1 },
  25. { _id: { month: 5, year: 2017 }, count: 1 }
  26. ]);
  27. await session.commitTransaction();
  28. session.endSession();