Skip to content

Commit

Permalink
Merge pull request #15093 from Automattic/vkarpov15/gh-15056
Browse files Browse the repository at this point in the history
fix(schema): throw error if duplicate index definition using `unique` in schema path and subsequent `.index()` call
  • Loading branch information
vkarpov15 authored Dec 16, 2024
2 parents b7b257e + f70e844 commit be5f054
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -2134,6 +2134,12 @@ Schema.prototype.index = function(fields, options) {
}
}

for (const existingIndex of this.indexes()) {
if (util.isDeepStrictEqual(existingIndex[0], fields)) {
throw new MongooseError(`Schema already has an index on ${JSON.stringify(fields)}`);
}
}

this._indexes.push([fields, options]);
return this;
};
Expand Down
17 changes: 17 additions & 0 deletions test/schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3278,4 +3278,21 @@ describe('schema', function() {
assert.ok(subdoc instanceof mongoose.Document);
assert.equal(subdoc.getAnswer(), 42);
});
it('throws "already has an index" error if duplicate index definition (gh-15056)', function() {
const ObjectKeySchema = new mongoose.Schema({
key: {
type: String,
required: true,
unique: true
},
type: {
type: String,
required: false
}
});

assert.throws(() => {
ObjectKeySchema.index({ key: 1 });
}, /MongooseError.*already has an index/);
});
});

0 comments on commit be5f054

Please sign in to comment.