Skip to content

Commit

Permalink
fix(populate): handle deselecting _id with array of fields in `popu…
Browse files Browse the repository at this point in the history
…late()`

Fix #14231
  • Loading branch information
vkarpov15 committed Jan 8, 2024
1 parent 2657417 commit 9b759bc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4298,6 +4298,8 @@ function populate(model, docs, options, callback) {
// _id back off before returning the result.
if (typeof select === 'string') {
select = select.replace(excludeIdRegGlobal, ' ');
} else if (Array.isArray(select)) {
select = select.filter(field => field !== '-_id');
} else {
// preserve original select conditions by copying
select = { ...select };
Expand Down
11 changes: 10 additions & 1 deletion test/model.populate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2197,7 +2197,7 @@ describe('model: populate:', function() {
});

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

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

doc = await U.findOne({ name: 'u1' }).populate('comments', ['-_id']);
assert.equal(doc.comments.length, 2);
doc.comments.forEach(function(d) {
assert.equal(d._id, undefined);
assert.equal(Object.keys(d._doc).indexOf('_id'), -1);
assert.ok(d.title.length);
assert.ok(d.body.length);
assert.equal(typeof d._doc.__v, 'number');
});
});

it('with lean', async function() {
Expand Down

0 comments on commit 9b759bc

Please sign in to comment.