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): deduplicate idGetter so creating multiple models with same schema doesn't result in multiple id getters #14492

Merged
merged 1 commit into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1916,6 +1916,7 @@ Schema.prototype.plugin = function(fn, opts) {
'got "' + (typeof fn) + '"');
}


if (opts && opts.deduplicate) {
for (const plugin of this.plugins) {
if (plugin.fn === fn) {
Expand Down Expand Up @@ -2720,7 +2721,7 @@ function isArrayFilter(piece) {
*/

Schema.prototype._preCompile = function _preCompile() {
idGetter(this);
this.plugin(idGetter, { deduplicate: true });
};

/*!
Expand Down
7 changes: 7 additions & 0 deletions test/schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3172,6 +3172,13 @@ describe('schema', function() {
const res = await Test.findOne({ _id: { $eq: doc._id, $type: 'objectId' } });
assert.equal(res.name, 'Test Testerson');
});
it('deduplicates idGetter (gh-14457)', function() {
const schema = new Schema({ name: String });
schema._preCompile();
assert.equal(schema.virtual('id').getters.length, 1);
schema._preCompile();
assert.equal(schema.virtual('id').getters.length, 1);
});

it('handles recursive definitions in discriminators (gh-13978)', function() {
const base = new Schema({
Expand Down
Loading