From 7e30a089c6b099b0f3380a2beaf5b93645b9c071 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 2 Apr 2024 15:28:52 -0400 Subject: [PATCH] fix(schema): deduplicate idGetter so creating multiple models with same schema doesn't result in multiple id getters Fix #14457 --- lib/schema.js | 3 ++- test/schema.test.js | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/schema.js b/lib/schema.js index 600e27208ee..dab8c273164 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -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) { @@ -2720,7 +2721,7 @@ function isArrayFilter(piece) { */ Schema.prototype._preCompile = function _preCompile() { - idGetter(this); + this.plugin(idGetter, { deduplicate: true }); }; /*! diff --git a/test/schema.test.js b/test/schema.test.js index 0df19a65790..c44452a5754 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -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({