Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(schema): throw error if duplicate index definition using unique in schema path and subsequent .index() call #15093

Merged
merged 3 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
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,

Check failure on line 3286 in test/schema.test.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Unexpected trailing comma
},
type: {
type: String,
required: false,

Check failure on line 3290 in test/schema.test.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Unexpected trailing comma
},

Check failure on line 3291 in test/schema.test.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Unexpected trailing comma
});

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