Skip to content

Commit

Permalink
fix(schema): load child class getter for virtuals instead of base cla…
Browse files Browse the repository at this point in the history
…ss when using `loadClass()`

Fix #9975
  • Loading branch information
vkarpov15 committed Mar 3, 2021
1 parent b23f4f1 commit 0f80ef8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1900,7 +1900,7 @@ Schema.prototype.loadClass = function(model, virtualsOnly) {
return this;
}

this.loadClass(Object.getPrototypeOf(model));
this.loadClass(Object.getPrototypeOf(model), virtualsOnly);

// Add static methods
if (!virtualsOnly) {
Expand All @@ -1927,9 +1927,15 @@ Schema.prototype.loadClass = function(model, virtualsOnly) {
}
}
if (typeof method.get === 'function') {
if (this.virtuals[name]) {
this.virtuals[name].getters = [];
}
this.virtual(name).get(method.get);
}
if (typeof method.set === 'function') {
if (this.virtuals[name]) {
this.virtuals[name].setters = [];
}
this.virtual(name).set(method.set);
}
}, this);
Expand Down
18 changes: 18 additions & 0 deletions test/schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2566,4 +2566,22 @@ describe('schema', function() {
assert.equal(schema.path('tags').caster.instance, 'String');
assert.equal(schema.path('subdocs').casterConstructor.schema.path('name').instance, 'String');
});

it('handles loadClass with inheritted getters (gh-9975)', function() {
class User {
get displayAs() {
return null;
}
}

class TechnicalUser extends User {
get displayAs() {
return this.name;
}
}

const schema = new Schema({ name: String }).loadClass(TechnicalUser);

assert.equal(schema.virtuals.displayAs.applyGetters(null, { name: 'test' }), 'test');
});
});

0 comments on commit 0f80ef8

Please sign in to comment.