Skip to content

Commit

Permalink
Merge pull request #14744 from Automattic/vkarpov15/gh-14736
Browse files Browse the repository at this point in the history
fix(model): support `session: null` option for `save()` to opt out of automatic `session` option with `transactionAsyncLocalStorage`
  • Loading branch information
vkarpov15 authored Jul 15, 2024
2 parents 1972f7f + 41b1ce3 commit 93ebbe1
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
5 changes: 3 additions & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
13 changes: 12 additions & 1 deletion test/docs/transactions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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);
});
});

Expand Down
2 changes: 1 addition & 1 deletion test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 93ebbe1

Please sign in to comment.