Skip to content

Commit

Permalink
feat: remove default connection if setting createInitialConnection to…
Browse files Browse the repository at this point in the history
… false after Mongoose instance created re: #8302
  • Loading branch information
vkarpov15 committed Jun 19, 2024
1 parent 174d8be commit b5e66ef
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const SetOptionError = require('./error/setOptionError');
const applyEmbeddedDiscriminators = require('./helpers/discriminator/applyEmbeddedDiscriminators');

const defaultMongooseSymbol = Symbol.for('mongoose:default');
const defaultConnectionSymbol = Symbol('mongoose:defaultConnection');

require('./helpers/printJestWarning');

Expand Down Expand Up @@ -73,6 +74,7 @@ function Mongoose(options) {
const createInitialConnection = utils.getOption('createInitialConnection', this.options) ?? true;
if (createInitialConnection && this.__driver != null) {
const conn = this.createConnection(); // default connection
conn[defaultConnectionSymbol] = true;
conn.models = this.models;
}

Expand Down Expand Up @@ -292,6 +294,16 @@ Mongoose.prototype.set = function(key, value) {
} else if (!optionValue && _mongoose.transactionAsyncLocalStorage) {
delete _mongoose.transactionAsyncLocalStorage;
}
} else if (optionKey === 'createInitialConnection') {
if (optionValue && !_mongoose.connection) {
const conn = this.createConnection(); // default connection
conn[defaultConnectionSymbol] = true;
conn.models = this.models;
} else if (optionValue === false && _mongoose.connection && _mongoose.connection[defaultConnectionSymbol]) {
if (_mongoose.connection.readyState === STATES.disconnected && Object.keys(_mongoose.connection.models).length === 0) {
_mongoose.connections.shift();
}
}
}
}

Expand Down
1 change: 1 addition & 0 deletions lib/validOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const VALID_OPTIONS = Object.freeze([
'bufferCommands',
'bufferTimeoutMS',
'cloneSchemas',
'createInitialConnection',
'debug',
'id',
'timestamps.createdAt.immutable',
Expand Down
10 changes: 10 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1180,4 +1180,14 @@ describe('mongoose module:', function() {
}
});
});

it('setting createInitialConnection after creation deletes existing connection (gh-8302)', async function() {
const m = new mongoose.Mongoose();
assert.ok(m.connection);
m.set('createInitialConnection', false);
assert.strictEqual(m.connection, undefined);

const conn = m.createConnection();
assert.equal(conn, m.connection);
});
});

0 comments on commit b5e66ef

Please sign in to comment.