Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(populate): handle deselecting _id with array of fields in populate() #14242

Merged
merged 1 commit into from Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/model.js
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
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