Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down
7 changes: 4 additions & 3 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -6784,12 +6785,12 @@ describe('Model', function() {
// 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);
});
});
Expand Down