Skip to content

Commit

Permalink
fix(model): make syncIndexes() handle changes in index key order
Browse files Browse the repository at this point in the history
Fix #8135
  • Loading branch information
vkarpov15 committed Sep 12, 2019
1 parent ce9d8d0 commit 6e86500
Showing 1 changed file with 38 additions and 16 deletions.
54 changes: 38 additions & 16 deletions lib/model.js
Expand Up @@ -1337,23 +1337,8 @@ Model.syncIndexes = function syncIndexes(options, callback) {
}

for (const schemaIndex of schemaIndexes) {
const key = schemaIndex[0];
const options = _decorateDiscriminatorIndexOptions(this,
utils.clone(schemaIndex[1]));

// If these options are different, need to rebuild the index
const optionKeys = ['unique', 'partialFilterExpression', 'sparse', 'expireAfterSeconds'];
const indexCopy = Object.assign({}, index);
for (const key of optionKeys) {
if (!(key in options) && !(key in indexCopy)) {
continue;
}
indexCopy[key] = options[key];
}
if (utils.deepEqual(key, index.key) &&
utils.deepEqual(index, indexCopy)) {
if (isIndexEqual(this, schemaIndex, index)) {
found = true;
break;
}
}

Expand Down Expand Up @@ -1406,6 +1391,43 @@ Model.syncIndexes = function syncIndexes(options, callback) {
}, this.events);
};

/*!
* ignore
*/

function isIndexEqual(model, schemaIndex, dbIndex) {
const key = schemaIndex[0];
const options = _decorateDiscriminatorIndexOptions(model,
utils.clone(schemaIndex[1]));

// If these options are different, need to rebuild the index
const optionKeys = ['unique', 'partialFilterExpression', 'sparse', 'expireAfterSeconds'];
for (const key of optionKeys) {
if (!(key in options) && !(key in dbIndex)) {
continue;
}
if (!utils.deepEqual(options[key], dbIndex[key])) {
return false;
}
}

const schemaIndexKeys = Object.keys(key);
const dbIndexKeys = Object.keys(dbIndex.key);
if (schemaIndexKeys.length !== dbIndexKeys.length) {
return false;
}
for (let i = 0; i < schemaIndexKeys.length; ++i) {
if (schemaIndexKeys[i] !== dbIndexKeys[i]) {
return false;
}
if (!utils.deepEqual(key[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) {
return false;
}
}

return true;
}

/**
* Lists the indexes currently defined in MongoDB. This may or may not be
* the same as the indexes defined in your schema depending on whether you
Expand Down

0 comments on commit 6e86500

Please sign in to comment.