From 08a30c7eaf6e7ce216b1ad5a7b8394587609cd91 Mon Sep 17 00:00:00 2001 From: Felix Reinhardt Date: Mon, 17 Aug 2020 16:19:20 +0200 Subject: [PATCH 1/3] Fix: Retaining null value for populated documents when _id is suppressed --- lib/helpers/populate/assignVals.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/helpers/populate/assignVals.js b/lib/helpers/populate/assignVals.js index 798482197db..c47172b0b25 100644 --- a/lib/helpers/populate/assignVals.js +++ b/lib/helpers/populate/assignVals.js @@ -243,7 +243,7 @@ function valueFilter(val, assignmentOpts, populateOptions) { */ function maybeRemoveId(subdoc, assignmentOpts) { - if (assignmentOpts.excludeId) { + if (subdoc != null && assignmentOpts.excludeId) { if (typeof subdoc.$__setValue === 'function') { delete subdoc._doc._id; } else { From bf1a9b492a986221f441f7276f9c944a2d733828 Mon Sep 17 00:00:00 2001 From: Felix Reinhardt Date: Mon, 17 Aug 2020 17:10:41 +0200 Subject: [PATCH 2/3] Add regression test for Issue #9336 --- test/model.populate.test.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/test/model.populate.test.js b/test/model.populate.test.js index ecf2a52e33e..f9055597a40 100644 --- a/test/model.populate.test.js +++ b/test/model.populate.test.js @@ -1626,6 +1626,33 @@ describe('model: populate:', function() { }); }); + it('supports `retainNullValues` while supressing _id of subdocument', function() { + const BlogPost = db.model('BlogPost', blogPostSchema); + const User = db.model('User', userSchema); + + return co(function*() { + const user = new User({ name: 'Victor Hugo' }); + yield user.save(); + const post = yield BlogPost.create({ + title: 'Notre-Dame de Paris', + fans: [] + }); + + yield BlogPost.collection.updateOne({ _id: post._id }, { + $set: { fans: [user.id] } + }); + + yield user.delete() + + const returned = yield BlogPost. + findById(post._id). + populate({ path: 'fans', select: 'name -_id', options: { retainNullValues: true } }); + + assert.equal(returned.fans.length, 1); + assert.strictEqual(returned.fans[0], null); + }); + }); + it('populating more than one array at a time', function(done) { const User = db.model('User', userSchema); const M = db.model('Test', new Schema({ From 01b48b5d3419fab07624f23bffe72cdf1e8db678 Mon Sep 17 00:00:00 2001 From: Felix Reinhardt Date: Mon, 17 Aug 2020 17:27:32 +0200 Subject: [PATCH 3/3] Fixed code style --- test/model.populate.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/model.populate.test.js b/test/model.populate.test.js index f9055597a40..3fdd83c76ee 100644 --- a/test/model.populate.test.js +++ b/test/model.populate.test.js @@ -1637,12 +1637,12 @@ describe('model: populate:', function() { title: 'Notre-Dame de Paris', fans: [] }); - + yield BlogPost.collection.updateOne({ _id: post._id }, { $set: { fans: [user.id] } }); - yield user.delete() + yield user.delete(); const returned = yield BlogPost. findById(post._id).