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(query): handle deselecting _id when another field has schema-level select: false #12736

Merged
merged 4 commits into from Nov 30, 2022
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
5 changes: 5 additions & 0 deletions lib/queryhelpers.js
Expand Up @@ -163,6 +163,11 @@ exports.applyPaths = function applyPaths(fields, schema) {
if (!isDefiningProjection(field)) {
continue;
}
// `_id: 1, name: 0` is a mixed inclusive/exclusive projection in
// MongoDB 4.0 and earlier, but not in later versions.
if (keys[keyIndex] === '_id' && keys.length > 1) {
continue;
}
exclude = !field;
break;
}
Expand Down
23 changes: 17 additions & 6 deletions test/model.field.selection.test.js
Expand Up @@ -475,7 +475,6 @@ describe('model field selection', function() {
db.deleteModel(/BlogPost/);
const BlogPost = db.model('BlogPost', BlogPostSchema);


await BlogPost.create({
author: 'me',
settings: {
Expand All @@ -497,8 +496,6 @@ describe('model field selection', function() {
});

it('when `select: true` in schema, works with $elemMatch in projection', async function() {


const productSchema = new Schema({
attributes: {
select: true,
Expand All @@ -524,12 +521,10 @@ describe('model field selection', function() {
});

it('selection specified in query overwrites option in schema', async function() {

const productSchema = new Schema({ name: { type: String, select: false } });

const Product = db.model('Product', productSchema);


await Product.create({ name: 'Computer' });

const product = await Product.findOne().select('name');
Expand All @@ -538,7 +533,6 @@ describe('model field selection', function() {
});

it('selecting with `false` instead of `0` doesn\'t overwrite schema `select: false` (gh-8923)', async function() {

const userSchema = new Schema({
name: { type: String, select: false },
age: { type: Number }
Expand All @@ -552,4 +546,21 @@ describe('model field selection', function() {

assert.ok(!user.name);
});

it('handles deselecting _id when other field has schema-level `select: false` (gh-12670)', async function() {
const schema = new mongoose.Schema({
field1: {
type: String,
select: false
},
field2: String
});
const User = db.model('User', schema);

await User.create({ field1: 'test1', field2: 'test2' });
const doc = await User.findOne().select('field2 -_id');
assert.ok(doc.field2);
assert.strictEqual(doc.field1, undefined);
assert.strictEqual(doc._id, undefined);
});
});