diff --git a/lib/model.js b/lib/model.js index 767c8e67121..507ec49ff1d 100644 --- a/lib/model.js +++ b/lib/model.js @@ -290,9 +290,10 @@ Model.prototype.$__handleSave = function(options, callback) { const session = this.$session(); const asyncLocalStorage = this[modelDbSymbol].base.transactionAsyncLocalStorage?.getStore(); - if (!saveOptions.hasOwnProperty('session') && session != null) { + if (session != null) { saveOptions.session = session; - } else if (asyncLocalStorage?.session != null) { + } else if (!options.hasOwnProperty('session') && asyncLocalStorage?.session != null) { + // Only set session from asyncLocalStorage if `session` option wasn't originally passed in options saveOptions.session = asyncLocalStorage.session; } if (this.$isNew) { diff --git a/test/docs/transactions.test.js b/test/docs/transactions.test.js index ab41a7063bc..2b19aef9ee3 100644 --- a/test/docs/transactions.test.js +++ b/test/docs/transactions.test.js @@ -370,7 +370,7 @@ describe('transactions', function() { await Test.createCollection(); await Test.deleteMany({}); - const doc = new Test({ name: 'test_transactionAsyncLocalStorage' }); + let doc = new Test({ name: 'test_transactionAsyncLocalStorage' }); await assert.rejects( () => m.connection.transaction(async() => { await doc.save(); @@ -402,6 +402,17 @@ describe('transactions', function() { exists = await Test.exists({ name: 'bar' }); assert.ok(!exists); + + doc = new Test({ name: 'test_transactionAsyncLocalStorage' }); + await assert.rejects( + () => m.connection.transaction(async() => { + await doc.save({ session: null }); + throw new Error('Oops!'); + }), + /Oops!/ + ); + exists = await Test.exists({ _id: doc._id }); + assert.ok(exists); }); }); diff --git a/test/document.test.js b/test/document.test.js index 0e7eae43e52..c11f72753ee 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -13746,7 +13746,7 @@ describe('document', function() { }); }); -describe('Check if instance function that is supplied in schema option is availabe', function() { +describe('Check if instance function that is supplied in schema option is available', function() { it('should give an instance function back rather than undefined', function ModelJS() { const testSchema = new mongoose.Schema({}, { methods: { instanceFn() { return 'Returned from DocumentInstanceFn'; } } }); const TestModel = mongoose.model('TestModel', testSchema);