diff --git a/lib/index.js b/lib/index.js index 4a3a4927f6f..eb1aa7db89a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -69,8 +69,11 @@ function Mongoose(options) { autoIndex: true, autoCreate: true }, options); - const conn = this.createConnection(); // default connection - conn.models = this.models; + const createInitialConnection = utils.getOption('createInitialConnection', this.options); + if (createInitialConnection == null || createInitialConnection) { + const conn = this.createConnection(); // default connection + conn.models = this.models; + } if (this.options.pluralization) { this._pluralize = legacyPluralize; diff --git a/test/connection.test.js b/test/connection.test.js index b38a3f33b96..ed65d720dfc 100644 --- a/test/connection.test.js +++ b/test/connection.test.js @@ -1525,4 +1525,11 @@ describe('connections:', function() { const connectionIds = m.connections.map(c => c.id); assert.deepEqual(connectionIds, [1, 2, 3, 4, 5]); }); + + it('should not create default connection with createInitialConnection = false (gh-12965)', function() { + const m = new mongoose.Mongoose({ + createInitialConnection: false + }); + assert.deepEqual(m.connections.length, 0); + }); }); diff --git a/types/mongooseoptions.d.ts b/types/mongooseoptions.d.ts index 2a42540670c..054f85e7606 100644 --- a/types/mongooseoptions.d.ts +++ b/types/mongooseoptions.d.ts @@ -63,6 +63,13 @@ declare module 'mongoose' { */ cloneSchemas?: boolean; + /** + * Set to `false` to disable the creation of the initial default connection. + * + * @default true + */ + createInitialConnection?: boolean; + /** * If `true`, prints the operations mongoose sends to MongoDB to the console. * If a writable stream is passed, it will log to that stream, without colorization.