From bc82f85783acf23be7c1c1a15aa8190808db8b2e Mon Sep 17 00:00:00 2001 From: Ryan Wheale Date: Mon, 15 Jul 2024 20:07:22 -0600 Subject: [PATCH 1/2] fix: allow non-discriminated documents be retrieved --- index.js | 4 +++- test/index.test.js | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index bd5148a..c7fa891 100644 --- a/index.js +++ b/index.js @@ -81,7 +81,9 @@ function getSchemaForDoc(schema, res) { break; } } - return childSchema; + + // If no discriminator schema found, return the root schema (#39) + return childSchema || schema; } function applyGettersToDoc(schema, doc, fields, prefix) { diff --git a/test/index.test.js b/test/index.test.js index 02f4c1b..8780120 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -384,4 +384,18 @@ describe('mongoose-lean-getters', function() { assert.equal(typeof doc.field, 'string'); assert.strictEqual(doc.field, '1337'); }); + + it('should allow non-discriminated documents to be retrieved (#39)', async() => { + const baseSchema = new mongoose.Schema({ foo: String }); + baseSchema.plugin(mongooseLeanGetters); + + const BaseModel = mongoose.model('BaseModel-gh-39', baseSchema); + BaseModel.discriminator('Custom', new mongoose.Schema({})); + + // Simply retrieving the non-discriminated document causes the error + await assert.doesNotReject(async() => { + const entry = await BaseModel.create({ foo: 'foo' }); + await BaseModel.findById({ _id: entry._id }).lean({ getters: true }); + }); + }); }); From aa5bf9987948930a0ce1ac583dc7f94deeb42d95 Mon Sep 17 00:00:00 2001 From: Ryan Wheale Date: Mon, 15 Jul 2024 20:14:54 -0600 Subject: [PATCH 2/2] chore: only pass id to find method --- test/index.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/index.test.js b/test/index.test.js index 8780120..f89ae77 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -395,7 +395,7 @@ describe('mongoose-lean-getters', function() { // Simply retrieving the non-discriminated document causes the error await assert.doesNotReject(async() => { const entry = await BaseModel.create({ foo: 'foo' }); - await BaseModel.findById({ _id: entry._id }).lean({ getters: true }); + await BaseModel.findById(entry._id).lean({ getters: true }); }); }); });