From 2553f516abda5232c8b1eaf03510047fa64bdc47 Mon Sep 17 00:00:00 2001 From: Sebastian Mayr Date: Thu, 20 Jun 2024 15:45:31 -0400 Subject: [PATCH] Fix errors on null value array types --- index.js | 7 ++++--- test/index.test.js | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index bd5148a..48b7def 100644 --- a/index.js +++ b/index.js @@ -124,16 +124,17 @@ function applyGettersToDoc(schema, doc, fields, prefix) { const pathExists = mpath.has(path, doc); if (pathExists) { - if (schematype.$isMongooseArray && !schematype.$isMongooseDocumentArray) { + const val = schematype.applyGetters(mpath.get(path, doc), doc, true); + if (val && schematype.$isMongooseArray && !schematype.$isMongooseDocumentArray) { mpath.set( path, - schematype.applyGetters(mpath.get(path, doc), doc, true).map(subdoc => { + val.map(subdoc => { return schematype.caster.applyGetters(subdoc, doc); }), doc ); } else { - mpath.set(path, schematype.applyGetters(mpath.get(path, doc), doc, true), doc); + mpath.set(path, val, doc); } } }); diff --git a/test/index.test.js b/test/index.test.js index 02f4c1b..59327cf 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -45,6 +45,22 @@ describe('mongoose-lean-getters', function() { assert.equal(doc.arr[0].test, 'baz'); }); + it('with nulled array', async function() { + const schema = mongoose.Schema({ + arr: [String] + }); + schema.plugin(mongooseLeanGetters); + + const Model = mongoose.model('withNulledArray', schema); + + await Model.deleteMany({}); + await Model.create({ arr: null }); + + const doc = await Model.findOne().lean({ getters: true }); + + assert.equal(doc.arr, null); + }); + it('only calls getters once with find() (gh-1)', async function() { const schema = mongoose.Schema({ name: {