From 6e5176aa8073bdc82c8dc1653b358537dee72410 Mon Sep 17 00:00:00 2001 From: Luca Pizzini Date: Sat, 11 Feb 2023 11:47:56 +0100 Subject: [PATCH 1/2] feat(index): added createInitialConnection option to Mongoose constructor closes #12965 --- lib/index.js | 7 +++++-- test/connection.test.js | 7 +++++++ types/mongooseoptions.d.ts | 7 +++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index 75051293bce..7060797440a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -71,8 +71,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) ?? true; + if (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 d27c7879605..bf8d06089a5 100644 --- a/test/connection.test.js +++ b/test/connection.test.js @@ -1526,4 +1526,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. From 92f5924eab9c01e7dc248f201b3434d50155eefc Mon Sep 17 00:00:00 2001 From: Luca Pizzini Date: Sat, 11 Feb 2023 11:56:57 +0100 Subject: [PATCH 2/2] fix: syntax error for node 12 --- lib/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index 7060797440a..d071cd9e4bb 100644 --- a/lib/index.js +++ b/lib/index.js @@ -71,8 +71,8 @@ function Mongoose(options) { autoIndex: true, autoCreate: true }, options); - const createInitialConnection = utils.getOption('createInitialConnection', this.options) ?? true; - if (createInitialConnection) { + const createInitialConnection = utils.getOption('createInitialConnection', this.options); + if (createInitialConnection == null || createInitialConnection) { const conn = this.createConnection(); // default connection conn.models = this.models; }