Skip to content

Commit

Permalink
fix(schema): deduplicate idGetter so creating multiple models with sa…
Browse files Browse the repository at this point in the history
…me schema doesn't result in multiple id getters

Fix #14457
  • Loading branch information
vkarpov15 committed Apr 4, 2024
1 parent 9afba5f commit f1ed8b1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
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

0 comments on commit f1ed8b1

Please sign in to comment.