From 68f82c22eeb755cd6f72e3f2fdb7815a58b26570 Mon Sep 17 00:00:00 2001 From: Nathan Knight Date: Fri, 2 Jun 2023 16:48:40 -0400 Subject: [PATCH] fix: correctly get schema for each element of a discriminated array and do not attempt to get the schema for null/undefined docs --- index.js | 11 +++++++---- test/index.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 92bb6d0..4cf281a 100644 --- a/index.js +++ b/index.js @@ -67,7 +67,7 @@ function applyGetters(schema, res, path) { } function getSchemaForDoc(schema, res) { - if (!schema.discriminatorMapping || !schema.discriminatorMapping.key) { + if (!schema.discriminatorMapping || !schema.discriminatorMapping.key || !schema.discriminators) { return schema; } @@ -81,15 +81,18 @@ function applyGettersToDoc(schema, doc, fields, prefix) { return; } - const schemaForDoc = getSchemaForDoc(schema, doc); - if (Array.isArray(doc)) { for (let i = 0; i < doc.length; ++i) { - applyGettersToDoc.call(this, schemaForDoc, doc[i], fields, prefix); + const currentDoc = doc[i]; + if (currentDoc == null) continue; + const schemaForDoc = getSchemaForDoc(schema, currentDoc); + applyGettersToDoc.call(this, schemaForDoc, currentDoc, fields, prefix); } return; } + const schemaForDoc = getSchemaForDoc(schema, doc); + schemaForDoc.eachPath((path, schematype) => { const pathWithPrefix = prefix ? prefix + '.' + path : path; if (this.selectedInclusively() && diff --git a/test/index.test.js b/test/index.test.js index 6d0f2ed..bca210f 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -249,4 +249,32 @@ describe('mongoose-lean-getters', function() { assert.equal(docs[0].url, 'https://www.test.com discriminator field'); }); + + it('should work on schemas with discriminators in arrays', async function() { + const options = { discriminatorKey: 'kind' }; + + const eventSchema = new mongoose.Schema({ time: Date }, options); + const clickedLinkSchema = new mongoose.Schema({ + url: { type: String, get: v => v + ' discriminator field' } + }); + eventSchema.discriminator('ClickedLink', clickedLinkSchema); + + const eventListSchema = new mongoose.Schema({ + events: [eventSchema], + }); + eventListSchema.plugin(mongooseLeanGetters); + const EventList = mongoose.model('EventList', eventListSchema); + + await EventList.deleteMany({}); + await EventList.create({ + events: [{ + kind: 'ClickedLink', + url: 'https://www.test.com' + }], + }); + + const docs = await EventList.find().lean({ getters: true }); + + assert.equal(docs[0].events[0].url, 'https://www.test.com discriminator field'); + }); });