Skip to content

Commit

Permalink
fix(virtualtype): use $locals for default virtual getter/setter rat…
Browse files Browse the repository at this point in the history
…her than top-level doc

Fix #12124
Re: #6262
  • Loading branch information
vkarpov15 committed Jul 25, 2022
1 parent abb3563 commit 83f55cb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/virtualtype.js
Expand Up @@ -49,10 +49,10 @@ VirtualType.prototype._applyDefaultGetters = function() {
const path = this.path;
const internalProperty = '$' + path;
this.getters.push(function() {
return this[internalProperty];
return this.$locals[internalProperty];
});
this.setters.push(function(v) {
this[internalProperty] = v;
this.$locals[internalProperty] = v;
});
};

Expand Down
28 changes: 28 additions & 0 deletions test/document.test.js
Expand Up @@ -11574,6 +11574,34 @@ describe('document', function() {
assert.ok(err);
assert.ok(err.errors['testProp.testSubProp.nested.from']);
});

it('supports virtuals named isValid (gh-12124) (gh-6262)', async function() {
const Schema = new mongoose.Schema({
test: String,
data: { sub: String }
});

Schema.virtual('isValid');

const Test = db.model('Test', Schema);
let doc = new Test();

assert.ok(doc.$isValid('test'));
await doc.save();

doc = await Test.findOne();

doc.set('isValid', true);
assert.ok(doc.$isValid('test'));

doc.set({ test: 'test' });
await doc.save();
assert.equal(doc.test, 'test');

doc.set({ data: { sub: 'sub' } });
await doc.save();
assert.equal(doc.data.sub, 'sub');
});
});

describe('Check if instance function that is supplied in schema option is availabe', function() {
Expand Down

0 comments on commit 83f55cb

Please sign in to comment.