Skip to content

Commit

Permalink
fix(model): support session: null option for save() to opt out of…
Browse files Browse the repository at this point in the history
… automatic `session` option with `transactionAsyncLocalStorage`

Fix #14736
  • Loading branch information
vkarpov15 committed Jul 11, 2024
1 parent 090297e commit 1f9fa4a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,9 @@ Model.prototype.$__handleSave = function(options, callback) {

const session = this.$session();
const asyncLocalStorage = this[modelDbSymbol].base.transactionAsyncLocalStorage?.getStore();
if (!saveOptions.hasOwnProperty('session') && session != null) {
if (!options.hasOwnProperty('session') && session != null) {
saveOptions.session = session;
} else if (asyncLocalStorage?.session != null) {
} else if (!options.hasOwnProperty('session') && asyncLocalStorage?.session != null) {
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 All @@ -397,6 +397,17 @@ describe('transactions', function() {

exists = await Test.exists({ name: 'foo' });
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 1f9fa4a

Please sign in to comment.