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

check discriminator existence before accessing schema in getModelsMapForPopulate #8878

Merged
merged 2 commits into from
Apr 30, 2020
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
5 changes: 3 additions & 2 deletions lib/helpers/populate/getModelsMapForPopulate.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,9 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
const discriminatorKey = schematype.caster.schema.options.discriminatorKey;
modelNames = [];
for (const subdoc of subdocs) {
const discriminatorValue = utils.getValue(discriminatorKey, subdoc);
const discriminatorSchema = schematype.caster.discriminators[discriminatorValue].schema;
const discriminatorName = utils.getValue(discriminatorKey, subdoc);
const discriminator = schematype.caster.discriminators[discriminatorName];
const discriminatorSchema = discriminator && discriminator.schema;
if (discriminatorSchema == null) {
continue;
}
Expand Down
30 changes: 30 additions & 0 deletions test/model.populate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9325,5 +9325,35 @@ describe('model: populate:', function() {
assert.ok(isLean(post.user));
});
});

it('can populate subdocs where one is discriminator and the other is not (gh-8837)', function() {
return co(function*() {
const eventSchema = new Schema({ }, { discriminatorKey: 'type' });
const eventsListSchema = new Schema({ events: [eventSchema] });

const clickEventSchema = new Schema({
modelName: { type: String, required: true },
productId: { type: Schema.ObjectId, refPath: 'events.modelName' }
});

const eventsSchemaType = eventsListSchema.path('events');
eventsSchemaType.discriminator('ClickEvent', clickEventSchema);

const EventsList = db.model('EventsList', eventsListSchema);
const Product = db.model('Product', new Schema({ name: String }));

const product = yield Product.create({ name: 'GTX 1050 Ti' });

yield EventsList.create({
events: [
{ },
{ type: 'ClickEvent', modelName: 'Product', productId: product._id }
]
});

const result = yield EventsList.findOne().populate('events.productId');
assert.equal(result.events[1].productId.name, 'GTX 1050 Ti');
});
});
});
});