From eddaebbc16a471638a33efb6094f1f8cafee5ecc Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 7 Mar 2024 17:37:23 -0500 Subject: [PATCH] BREAKING CHANGE: call getters correctly on array elements for Mongoose 7.5.0, require Mongoose 7.5.0 Fix #30 --- index.js | 16 ++++++++++++++-- test/index.test.js | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 92bb6d0..eafe0fe 100644 --- a/index.js +++ b/index.js @@ -104,8 +104,20 @@ function applyGettersToDoc(schema, doc, fields, prefix) { !this.isPathSelectedInclusive(pathWithPrefix)) { return; } - if (mpath.has(path, doc)) { - mpath.set(path, schematype.applyGetters(mpath.get(path, doc), doc, true), doc); + + const pathExists = mpath.has(path, doc); + if (pathExists) { + if (schematype.$isMongooseArray && !schematype.$isMongooseDocumentArray) { + mpath.set( + path, + schematype.applyGetters(mpath.get(path, doc), doc, true).map(subdoc => { + return schematype.caster.applyGetters(subdoc, doc); + }), + doc + ); + } else { + mpath.set(path, schematype.applyGetters(mpath.get(path, doc), doc, true), doc); + } } }); } diff --git a/test/index.test.js b/test/index.test.js index 5bab752..28093f7 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -249,4 +249,30 @@ describe('mongoose-lean-getters', function() { assert.equal(docs[0].url, 'https://www.test.com discriminator field'); }); + + it('should call getters on arrays (gh-30)', async function() { + function upper(value) { + return value.toUpperCase(); + } + + const userSchema = new mongoose.Schema({ + name: { + type: String, + get: upper + }, + emails: [{ type: String, get: upper }] + }); + userSchema.plugin(mongooseLeanGetters); + const User = mongoose.model('User', userSchema); + + const user = new User({ + name: 'one', + emails: ['two', 'three'], + }); + await user.save(); + + const foundUser = await User.findById(user._id).lean({ getters: true }); + assert.strictEqual(user.name, 'ONE'); + assert.deepStrictEqual(foundUser.emails, ['TWO', 'THREE']); + }); });