From abb356373031b34a73bd8db3d76d623a30a7d96f Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 25 Jul 2022 16:52:58 -0400 Subject: [PATCH] fix(document): call subdocument getters if child schema has getters: true Fix #12105 --- lib/document.js | 4 ++-- test/document.test.js | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/document.js b/lib/document.js index f045a21f0ff..0340dbd9155 100644 --- a/lib/document.js +++ b/lib/document.js @@ -3642,10 +3642,10 @@ Document.prototype.$toObject = function(options, json) { options.minimize = _minimize; cloneOptions._parentOptions = options; - cloneOptions._skipSingleNestedGetters = true; + cloneOptions._skipSingleNestedGetters = false; const gettersOptions = Object.assign({}, cloneOptions); - gettersOptions._skipSingleNestedGetters = false; + gettersOptions._skipSingleNestedGetters = true; // remember the root transform function // to save it from being overwritten by sub-transform functions diff --git a/test/document.test.js b/test/document.test.js index 359a0ee050d..f3ffb9dee74 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -5426,8 +5426,29 @@ describe('document', function() { doc.toObject({ getters: false }); assert.equal(called, 1); + }); - return Promise.resolve(); + it('calls subdocument getters if child schema has getters: true (gh-12105)', function() { + let called = 0; + + const childSchema = new Schema({ + _id: false, + value: { + type: String, + get: function(v) { + ++called; + return v.toUpperCase(); + } + } + }, { toJSON: { getters: true } }); + const schema = new Schema({ name: childSchema }); + const Test = db.model('Test', schema); + + const doc = new Test({ name: { value: 'John Smith' } }); + + const res = doc.toJSON(); + assert.equal(called, 1); + assert.deepStrictEqual(res.name, { value: 'JOHN SMITH' }); }); it('setting doc array to array of top-level docs works (gh-5632)', function(done) {