From d5f5afe7fa4bcb45542ae85614daa9966fea1369 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 12 May 2025 16:13:03 -0400 Subject: [PATCH 1/2] fix: don't apply getters if defaultLeanOptions is set but lean is false Fix #46 --- index.js | 5 ++++- test/index.test.js | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 56b6abe..524bf8d 100644 --- a/index.js +++ b/index.js @@ -42,8 +42,11 @@ function applyGetters(schema, res) { if (res == null) { return; } + if (!this._mongooseOptions?.lean) { + return; + } const { defaultLeanOptions } = this._mongooseLeanGettersOptions; - const shouldCallGetters = this._mongooseOptions?.lean?.getters ?? defaultLeanOptions?.getters ?? false; + const shouldCallGetters = this._mongooseOptions.lean.getters ?? defaultLeanOptions?.getters ?? false; if (shouldCallGetters) { if (Array.isArray(res)) { diff --git a/test/index.test.js b/test/index.test.js index 048e786..4ea2962 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -442,7 +442,8 @@ describe('mongoose-lean-getters', function() { assert.equal(typeof found.discriminatedProp.num, 'string', 'Discriminated prop is not a string'); assert.equal(typeof found.discriminatedArray[0].num, 'string', 'Discriminated array is not a string'); }); - it('allows defaultLeanOptions to be set and overridden at call time (#33)', async() => { + + it('allows defaultLeanOptions to be set and overridden at call time (#33) (#46)', async() => { const testSchema = new mongoose.Schema({ field: { type: String, @@ -458,6 +459,10 @@ describe('mongoose-lean-getters', function() { const doc2 = await TestModel.findById(entry._id).lean({ getters: false }); assert.equal(doc2.field, 'value'); + + const doc3 = await TestModel.findById(entry._id); + assert.equal(doc3.field, 'value-suffix'); + assert.equal(doc3.get('field', null, { getters: false }), 'value'); }); it('should allow non-discriminated documents to be retrieved (#39)', async() => { From 5a2490051ff1359edafc0a9a186e5d882f25ba5c Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 12 May 2025 16:16:14 -0400 Subject: [PATCH 2/2] Update index.js Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- index.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/index.js b/index.js index 524bf8d..f3f6f0f 100644 --- a/index.js +++ b/index.js @@ -42,6 +42,8 @@ function applyGetters(schema, res) { if (res == null) { return; } + // Skip applying getters if the `lean` option is false. + // This ensures that Mongoose getters are not applied to non-lean queries. if (!this._mongooseOptions?.lean) { return; }