Skip to content

Commit

Permalink
fix(model): prevent index creation on syncIndexes if not necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
lpizzinidev committed Dec 9, 2022
1 parent 82943da commit f3dbd45
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
15 changes: 12 additions & 3 deletions lib/model.js
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
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

0 comments on commit f3dbd45

Please sign in to comment.