Skip to content

Commit 93ebbe1

Browse files
authored
Merge pull request #14744 from Automattic/vkarpov15/gh-14736
fix(model): support `session: null` option for `save()` to opt out of automatic `session` option with `transactionAsyncLocalStorage`
2 parents 1972f7f + 41b1ce3 commit 93ebbe1

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

lib/model.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -290,9 +290,10 @@ Model.prototype.$__handleSave = function(options, callback) {
290290

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

test/docs/transactions.test.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ describe('transactions', function() {
370370
await Test.createCollection();
371371
await Test.deleteMany({});
372372

373-
const doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
373+
let doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
374374
await assert.rejects(
375375
() => m.connection.transaction(async() => {
376376
await doc.save();
@@ -402,6 +402,17 @@ describe('transactions', function() {
402402

403403
exists = await Test.exists({ name: 'bar' });
404404
assert.ok(!exists);
405+
406+
doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
407+
await assert.rejects(
408+
() => m.connection.transaction(async() => {
409+
await doc.save({ session: null });
410+
throw new Error('Oops!');
411+
}),
412+
/Oops!/
413+
);
414+
exists = await Test.exists({ _id: doc._id });
415+
assert.ok(exists);
405416
});
406417
});
407418

test/document.test.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -13746,7 +13746,7 @@ describe('document', function() {
1374613746
});
1374713747
});
1374813748

13749-
describe('Check if instance function that is supplied in schema option is availabe', function() {
13749+
describe('Check if instance function that is supplied in schema option is available', function() {
1375013750
it('should give an instance function back rather than undefined', function ModelJS() {
1375113751
const testSchema = new mongoose.Schema({}, { methods: { instanceFn() { return 'Returned from DocumentInstanceFn'; } } });
1375213752
const TestModel = mongoose.model('TestModel', testSchema);

0 commit comments

Comments
 (0)