From 44dd2ddc110ca66d60077ade9760fa04c2965cb3 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 24 Feb 2025 16:35:30 -0500 Subject: [PATCH] fix: handle getter for single nested that returns non-object #42 --- index.js | 2 +- test/index.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index b983f27..8072ba8 100644 --- a/index.js +++ b/index.js @@ -117,7 +117,7 @@ function applyGettersToDoc(schema, doc) { val[i] = schematype.caster.applyGetters(val[i], doc); } } - } if (val && schematype.$isSingleNested) { + } if (val && typeof val === 'object' && schematype.$isSingleNested) { applyGettersToDoc.call(this, schematype.schema, val); } else { mpath.set(path, val, doc); diff --git a/test/index.test.js b/test/index.test.js index 3d120b1..9e7e696 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -526,4 +526,28 @@ describe('mongoose-lean-getters', function() { }) ); }); + + it('handles single nested getter that returns primitive (gh-42)', async function() { + const AccountSchema = new mongoose.Schema({ + name: { + _id: false, + type: { + first: { type: String, required: true }, + last: { type: String, required: true }, + }, + get: function(v) { + return v.first + v.last; + }, + }, + }); + AccountSchema.plugin(mongooseLeanGetters); + const Account = mongoose.model('gh-42-subdoc-getter', AccountSchema); + const { _id } = await Account.create({ + name: { first: 'Hamo', last: 'Boker' }, + }); + const account = await Account.findById(_id).lean({ + getters: true, + }); + assert.strictEqual(account.name, 'HamoBoker'); + }); });