diff --git a/lib/helpers/populate/assignVals.js b/lib/helpers/populate/assignVals.js index 33c618dc37c..81ccf61bc88 100644 --- a/lib/helpers/populate/assignVals.js +++ b/lib/helpers/populate/assignVals.js @@ -43,6 +43,9 @@ module.exports = function assignVals(o) { if (val instanceof SkipPopulateValue) { return val.val; } + if (val === void 0) { + return val; + } const _allIds = o.allIds[i]; diff --git a/lib/helpers/populate/lookupLocalFields.js b/lib/helpers/populate/lookupLocalFields.js index 7fcfae561c6..ea641bf8453 100644 --- a/lib/helpers/populate/lookupLocalFields.js +++ b/lib/helpers/populate/lookupLocalFields.js @@ -13,6 +13,9 @@ module.exports = function lookupLocalFields(cur, path, val) { if (typeof cur !== 'object') { return void 0; } + if (val === void 0) { + return void 0; + } cur[path] = val; return val; } diff --git a/test/model.populate.test.js b/test/model.populate.test.js index 6bedbc3e623..e1621e6007b 100644 --- a/test/model.populate.test.js +++ b/test/model.populate.test.js @@ -10565,4 +10565,41 @@ describe('model: populate:', function() { assert.equal(populatedBooks[0].author.name, 'Author1'); }); }); + + it('avoids setting empty array on lean document when populate result is undefined (gh-10599)', function() { + return co(function*() { + const ImageSchema = Schema({ imageName: String }, { _id: false }); + const TextSchema = Schema({ + textName: String, + attached: [{ type: 'ObjectId', ref: 'Test2' }] + }, { _id: false }); + + const ItemSchema = Schema({ objectType: String }, { + discriminatorKey: 'objectType', + _id: false + }); + + const ExampleSchema = Schema({ test: String, list: [ItemSchema] }); + + ExampleSchema.path('list').discriminator('Image', ImageSchema); + ExampleSchema.path('list').discriminator('Text', TextSchema); + const Example = db.model('Test', ExampleSchema); + const Another = db.model('Test2', Schema({ test: 'String' })); + + yield Another.create({ _id: '61254490ea89de0004c8f2a0', test: 'test' }); + + const example = yield Example.create({ + test: 'example', + list: [ + { imageName: 'an image', objectType: 'Image' }, + { textName: 'this is a text', attached: ['61254490ea89de0004c8f2a0'], objectType: 'Text' } + ] + }); + const query = Example.findById(example._id).populate('list.attached').lean(); + + const result = yield query.exec(); + assert.strictEqual(result.list[0].attached, void 0); + assert.equal(result.list[1].attached[0].test, 'test'); + }); + }); });