From 83f55cb582198200127f706552a2fff4bf5301d2 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 25 Jul 2022 17:10:36 -0400 Subject: [PATCH] fix(virtualtype): use `$locals` for default virtual getter/setter rather than top-level doc Fix #12124 Re: #6262 --- lib/virtualtype.js | 4 ++-- test/document.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/virtualtype.js b/lib/virtualtype.js index df576ccd384..d52f91dfb1d 100644 --- a/lib/virtualtype.js +++ b/lib/virtualtype.js @@ -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; }); }; diff --git a/test/document.test.js b/test/document.test.js index f3ffb9dee74..7a964ad33b9 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -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() {