Skip to content

Commit 131d13c

Browse files
authoredApr 4, 2024
Merge pull request #14492 from Automattic/vkarpov15/gh-14457
fix(schema): deduplicate idGetter so creating multiple models with same schema doesn't result in multiple id getters
2 parents b11ed34 + 7e30a08 commit 131d13c

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed
 

‎lib/schema.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -1952,6 +1952,7 @@ Schema.prototype.plugin = function(fn, opts) {
19521952
'got "' + (typeof fn) + '"');
19531953
}
19541954

1955+
19551956
if (opts && opts.deduplicate) {
19561957
for (const plugin of this.plugins) {
19571958
if (plugin.fn === fn) {
@@ -2755,7 +2756,7 @@ function isArrayFilter(piece) {
27552756
*/
27562757

27572758
Schema.prototype._preCompile = function _preCompile() {
2758-
idGetter(this);
2759+
this.plugin(idGetter, { deduplicate: true });
27592760
};
27602761

27612762
/*!

‎test/schema.test.js

+7
Original file line numberDiff line numberDiff line change
@@ -3172,6 +3172,13 @@ describe('schema', function() {
31723172
const res = await Test.findOne({ _id: { $eq: doc._id, $type: 'objectId' } });
31733173
assert.equal(res.name, 'Test Testerson');
31743174
});
3175+
it('deduplicates idGetter (gh-14457)', function() {
3176+
const schema = new Schema({ name: String });
3177+
schema._preCompile();
3178+
assert.equal(schema.virtual('id').getters.length, 1);
3179+
schema._preCompile();
3180+
assert.equal(schema.virtual('id').getters.length, 1);
3181+
});
31753182

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

0 commit comments

Comments
 (0)