Skip to content

Commit be5f054

Browse files
authored
Merge pull request Automattic#15093 from Automattic/vkarpov15/Automatticgh-15056
fix(schema): throw error if duplicate index definition using `unique` in schema path and subsequent `.index()` call
2 parents b7b257e + f70e844 commit be5f054

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

lib/schema.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2134,6 +2134,12 @@ Schema.prototype.index = function(fields, options) {
21342134
}
21352135
}
21362136

2137+
for (const existingIndex of this.indexes()) {
2138+
if (util.isDeepStrictEqual(existingIndex[0], fields)) {
2139+
throw new MongooseError(`Schema already has an index on ${JSON.stringify(fields)}`);
2140+
}
2141+
}
2142+
21372143
this._indexes.push([fields, options]);
21382144
return this;
21392145
};

test/schema.test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3278,4 +3278,21 @@ describe('schema', function() {
32783278
assert.ok(subdoc instanceof mongoose.Document);
32793279
assert.equal(subdoc.getAnswer(), 42);
32803280
});
3281+
it('throws "already has an index" error if duplicate index definition (gh-15056)', function() {
3282+
const ObjectKeySchema = new mongoose.Schema({
3283+
key: {
3284+
type: String,
3285+
required: true,
3286+
unique: true
3287+
},
3288+
type: {
3289+
type: String,
3290+
required: false
3291+
}
3292+
});
3293+
3294+
assert.throws(() => {
3295+
ObjectKeySchema.index({ key: 1 });
3296+
}, /MongooseError.*already has an index/);
3297+
});
32813298
});

0 commit comments

Comments
 (0)