From 4d4bd00f6c91c79ade43035616586b833f4965a7 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 3 Jan 2025 10:25:37 -0500 Subject: [PATCH] fix(model): skip createCollection() in syncIndexes() if autoCreate: false --- lib/model.js | 20 +++++++++++--------- test/model.test.js | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/lib/model.js b/lib/model.js index 67ccfb83a6..f4516a4967 100644 --- a/lib/model.js +++ b/lib/model.js @@ -1246,19 +1246,21 @@ Model.syncIndexes = async function syncIndexes(options) { throw new MongooseError('Model.syncIndexes() no longer accepts a callback'); } - const model = this; + const autoCreate = options?.autoCreate ?? this.schema.options?.autoCreate ?? this.db.config.autoCreate ?? true; - try { - await model.createCollection(); - } catch (err) { - if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) { - throw err; + if (autoCreate) { + try { + await this.createCollection(); + } catch (err) { + if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) { + throw err; + } } } - const diffIndexesResult = await model.diffIndexes(); - const dropped = await model.cleanIndexes({ ...options, toDrop: diffIndexesResult.toDrop }); - await model.createIndexes({ ...options, toCreate: diffIndexesResult.toCreate }); + const diffIndexesResult = await this.diffIndexes(); + const dropped = await this.cleanIndexes({ ...options, toDrop: diffIndexesResult.toDrop }); + await this.createIndexes({ ...options, toCreate: diffIndexesResult.toCreate }); return dropped; }; diff --git a/test/model.test.js b/test/model.test.js index e6a1ef9cd3..f011b22d2e 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -4885,6 +4885,28 @@ describe('Model', function() { assert.deepStrictEqual(indexes.map(index => index.name), ['_id_', 'name_1']); }); + it('avoids creating collection if autoCreate: false', async() => { + const collectionName = generateRandomCollectionName(); + const userSchema = new Schema( + { name: { type: String, index: true } }, + { autoIndex: false, autoCreate: false, collation: { locale: 'en_US', strength: 2 } } + ); + const User = db.model('User', userSchema, collectionName); + + // Act + await User.syncIndexes(); + + // Assert + const indexes = await User.listIndexes(); + assert.deepStrictEqual(indexes.map(index => index.name), ['_id_', 'name_1']); + + const collections = await User.db.listCollections(); + const collection = collections.find(c => c.name === collectionName); + assert.ok(collection); + // Collation was not applied because autoCreate was false, so Mongoose did not send `createCollection()` + assert.ok(!collection.options.collation); + }); + it('drops indexes that are not present in schema', async() => { // Arrange const collectionName = generateRandomCollectionName();