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(document): avoid stripping out fields in discriminator schema after select: false field #15322

Merged
merged 2 commits into from
Mar 21, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -747,16 +747,16 @@ function init(self, obj, doc, opts, prefix) {
for (let index = 0; index < len; ++index) {
i = keys[index];
// avoid prototype pollution
if (i === '__proto__' || i === 'constructor') {
return;
if (specialProperties.has(i)) {
continue;
}
path = prefix ? prefix + i : i;
schemaType = docSchema.path(path);
// Should still work if not a model-level discriminator, but should not be
// necessary. This is *only* to catch the case where we queried using the
// base model and the discriminated model has a projection
if (docSchema.$isRootDiscriminator && !self.$__isSelected(path)) {
return;
continue;
}

const value = obj[i];
Expand Down Expand Up @@ -1720,7 +1720,7 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
const last = next === l;
cur += (cur ? '.' + parts[i] : parts[i]);
if (specialProperties.has(parts[i])) {
return;
continue;
}

if (last) {
Expand Down
33 changes: 33 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14422,6 +14422,39 @@ describe('document', function() {
sinon.restore();
}
});

it('handles selected paths on root discriminator (gh-15308)', async function() {
const CarSchema = new mongoose.Schema(
{
make: {
type: String,
enum: ['mercedes']
}
},
{
discriminatorKey: 'make'
}
);
const MercedesSchema = new mongoose.Schema({
vin: {
type: String,
select: false
},
sunroof: Boolean
});
const CarModel = db.model('Car', CarSchema);
CarModel.discriminator('Car:mercedes', MercedesSchema, 'mercedes');

const newCar = await CarModel.create({
make: 'mercedes',
vin: 'someFakeVin',
sunroof: true
});

const car = await CarModel.findById(newCar._id);
assert.strictEqual(car.vin, undefined);
assert.strictEqual(car.sunroof, true);
});
});

describe('Check if instance function that is supplied in schema option is available', function() {
Expand Down
Loading