diff --git a/lib/model.js b/lib/model.js index a9a0784c50e..a1a96ebf6b8 100644 --- a/lib/model.js +++ b/lib/model.js @@ -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; } } @@ -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