Skip to content

Commit

Permalink
TransactionOptions support within transaction wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
pnutmath committed Jan 19, 2021
1 parent 6b65d0d commit 3bce4d9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -448,22 +448,23 @@ Connection.prototype.startSession = _wrapConnHelper(function startSession(option
*
* // Throw an error to abort the transaction
* throw new Error('Oops!');
* }).catch(() => {});
* },{ readPreference: 'primary' }).catch(() => {});
*
* // true, `transaction()` reset the document's state because the
* // transaction was aborted.
* doc.isNew;
*
* @method transaction
* @param {Function} fn Function to execute in a transaction
* @param {mongodb.TransactionOptions} [options] Optional settings for the transaction
* @return {Promise<Any>} promise that resolves to the returned value of `fn`
* @api public
*/

Connection.prototype.transaction = function transaction(fn) {
Connection.prototype.transaction = function transaction(fn, options) {
return this.startSession().then(session => {
session[sessionNewDocuments] = new Map();
return session.withTransaction(() => fn(session)).
return session.withTransaction(() => fn(session), options).
then(res => {
delete session[sessionNewDocuments];
return res;
Expand Down
17 changes: 17 additions & 0 deletions test/es-next/transactions.test.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -419,4 +419,21 @@ describe('transactions', function() {
const createdDoc = await Test.collection.findOne();
assert.deepEqual(createdDoc.arr, ['foo']);
});

it('can save a new document with an array and read within transaction', async function () {
const schema = Schema({ arr: [String] });

const Test = db.model('new_doc_array', schema);

await Test.createCollection();
const doc = new Test({ arr: ['foo'] });
await db.transaction(
async (session) => {
await doc.save({ session });
const testDocs = await Test.collection.find({}).session(session);
assert.deepStrictEqual(testDocs.length, 1);
},
{ readPreference: 'primary' }
);
});
});

0 comments on commit 3bce4d9

Please sign in to comment.