diff --git a/lib/model.js b/lib/model.js index 382e0af2d09..51d33bf5a41 100644 --- a/lib/model.js +++ b/lib/model.js @@ -1570,14 +1570,14 @@ Model.diffIndexes = function diffIndexes(options, callback) { const schemaIndexes = getRelatedSchemaIndexes(model, schema.indexes()); const toDrop = getIndexesToDrop(schema, schemaIndexes, dbIndexes); - const toCreate = getIndexesToCreate(schema, schemaIndexes, dbIndexes); + const toCreate = getIndexesToCreate(schema, schemaIndexes, dbIndexes, toDrop); cb(null, { toDrop, toCreate }); }); }); }; -function getIndexesToCreate(schema, schemaIndexes, dbIndexes) { +function getIndexesToCreate(schema, schemaIndexes, dbIndexes, toDrop) { const toCreate = []; for (const [schemaIndexKeysObject, schemaIndexOptions] of schemaIndexes) { @@ -1589,7 +1589,10 @@ function getIndexesToCreate(schema, schemaIndexes, dbIndexes) { if (isDefaultIdIndex(index)) { continue; } - if (isIndexEqual(schemaIndexKeysObject, options, index)) { + if ( + isIndexEqual(schemaIndexKeysObject, options, index) && + !toDrop.includes(index.name) + ) { found = true; break; } @@ -1887,6 +1890,12 @@ function _ensureIndexes(model, options, callback) { indexOptions.background = options.background; } + if ('toCreate' in options) { + if (options.toCreate.length === 0) { + return done(); + } + } + model.collection.createIndex(indexFields, indexOptions, utils.tick(function(err, name) { indexSingleDone(err, indexFields, indexOptions, name); if (err) { diff --git a/test/model.test.js b/test/model.test.js index 3c6585db5ce..6157f53e3b5 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -6767,7 +6767,8 @@ describe('Model', function() { ); }); - xit('creates indexes only when they do not exist on the mongodb server (gh-12250)', async() => { + + it('creates indexes only when they do not exist on the mongodb server (gh-12250)', async() => { const userSchema = new Schema({ name: { type: String } }, { autoIndex: false }); @@ -6781,15 +6782,14 @@ describe('Model', function() { const createIndexSpy = sinon.spy(User.collection, 'createIndex'); const listIndexesSpy = sinon.spy(User.collection, 'listIndexes'); - // Act await User.syncIndexes(); + assert.equal(createIndexSpy.callCount, 1); - assert.equal(listIndexesSpy.callCount, 2); + assert.equal(listIndexesSpy.callCount, 1); await User.syncIndexes(); - // Assert - assert.equal(listIndexesSpy.callCount, 4); + assert.equal(listIndexesSpy.callCount, 2); assert.equal(createIndexSpy.callCount, 1); }); });