Skip to content

Commit 9b759bc

Browse files
committed
fix(populate): handle deselecting _id with array of fields in populate()
Fix #14231
1 parent 2657417 commit 9b759bc

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/model.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4298,6 +4298,8 @@ function populate(model, docs, options, callback) {
42984298
// _id back off before returning the result.
42994299
if (typeof select === 'string') {
43004300
select = select.replace(excludeIdRegGlobal, ' ');
4301+
} else if (Array.isArray(select)) {
4302+
select = select.filter(field => field !== '-_id');
43014303
} else {
43024304
// preserve original select conditions by copying
43034305
select = { ...select };

test/model.populate.test.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2197,7 +2197,7 @@ describe('model: populate:', function() {
21972197
});
21982198

21992199
describe('in a subdocument', function() {
2200-
it('works', async function() {
2200+
it('works (gh-14231)', async function() {
22012201
const docs = await U.find({ name: 'u1' }).populate('comments', { _id: 0 });
22022202

22032203
let doc = docs[0];
@@ -2229,6 +2229,15 @@ describe('model: populate:', function() {
22292229
assert.equal(typeof d._doc.__v, 'number');
22302230
});
22312231

2232+
doc = await U.findOne({ name: 'u1' }).populate('comments', ['-_id']);
2233+
assert.equal(doc.comments.length, 2);
2234+
doc.comments.forEach(function(d) {
2235+
assert.equal(d._id, undefined);
2236+
assert.equal(Object.keys(d._doc).indexOf('_id'), -1);
2237+
assert.ok(d.title.length);
2238+
assert.ok(d.body.length);
2239+
assert.equal(typeof d._doc.__v, 'number');
2240+
});
22322241
});
22332242

22342243
it('with lean', async function() {

0 commit comments

Comments
 (0)