Skip to content

Commit e909e0b

Browse files
committed
fix: support session: null option for save() to opt out of automatic session option with transactionAsyncLocalStorage; backport #14744
1 parent 3f21bfa commit e909e0b

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

lib/model.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,9 +289,10 @@ Model.prototype.$__handleSave = function(options, callback) {
289289

290290
const session = this.$session();
291291
const asyncLocalStorage = this[modelDbSymbol].base.transactionAsyncLocalStorage?.getStore();
292-
if (!saveOptions.hasOwnProperty('session') && session != null) {
292+
if (session != null) {
293293
saveOptions.session = session;
294-
} else if (asyncLocalStorage?.session != null) {
294+
} else if (!options.hasOwnProperty('session') && asyncLocalStorage?.session != null) {
295+
// Only set session from asyncLocalStorage if `session` option wasn't originally passed in options
295296
saveOptions.session = asyncLocalStorage.session;
296297
}
297298

test/docs/transactions.test.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ describe('transactions', function() {
441441
await Test.createCollection();
442442
await Test.deleteMany({});
443443

444-
const doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
444+
let doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
445445
await assert.rejects(
446446
() => m.connection.transaction(async() => {
447447
await doc.save();
@@ -473,6 +473,17 @@ describe('transactions', function() {
473473

474474
exists = await Test.exists({ name: 'bar' });
475475
assert.ok(!exists);
476+
477+
doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
478+
await assert.rejects(
479+
() => m.connection.transaction(async() => {
480+
await doc.save({ session: null });
481+
throw new Error('Oops!');
482+
}),
483+
/Oops!/
484+
);
485+
exists = await Test.exists({ _id: doc._id });
486+
assert.ok(exists);
476487
});
477488
});
478489
});

0 commit comments

Comments
 (0)