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:

  1. import mongoose from 'mongoose';

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

  1. // Using Mongoose's default connection
  2. const session = await mongoose.startSession();
  3. // Using custom connection
  4. const db = await mongoose.createConnection(mongodbUri);
  5. 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.
  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.

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.

  1. const schema = Schema({ name: String, arr: [String], arr2: [String] });
  2. const Test = db.model('Test', schema);
  3. await Test.createCollection();
  4. let doc = await Test.create({ name: 'foo', arr: ['bar'], arr2: ['foo'] });
  5. doc = await Test.findById(doc);
  6. await db.
  7. transaction(async (session) => {
  8. doc.arr.pull('bar');
  9. doc.arr2.push('bar');
  10. await doc.save({ session });
  11. doc.name = 'baz';
  12. throw new Error('Oops');
  13. }).
  14. catch(err => {
  15. assert.equal(err.message, 'Oops');
  16. });
  17. const changes = doc.getChanges();
  18. assert.equal(changes.$set.name, 'baz');
  19. assert.deepEqual(changes.$pullAll.arr, ['bar']);
  20. assert.deepEqual(changes.$push.arr2, { $each: ['bar'] });
  21. assert.ok(!changes.$set.arr2);
  22. await doc.save({ session: null });
  23. const newDoc = await Test.findById(doc);
  24. assert.equal(newDoc.name, 'baz');
  25. assert.deepEqual(newDoc.arr, []);
  26. assert.deepEqual(newDoc.arr2, ['foo', 'bar']);

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. await session.withTransaction(async () => {
  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. const doc = await User.findOne({ name: 'bar' });
  13. assert.ok(!doc);
  14. });
  15. session.endSession();
  16. const 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. await session.withTransaction(async () => {
  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. });
  28. session.endSession();

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:

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

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

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