Skip to content

Commit

Permalink
Merge pull request #8878 from AbdelrahmanHafez/gh-8837-master
Browse files Browse the repository at this point in the history
check discriminator existence before accessing schema in getModelsMapForPopulate
  • Loading branch information
vkarpov15 authored Apr 30, 2020
2 parents 07d04e3 + 760b1e5 commit 872ab26
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
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');
});
});
});
});

0 comments on commit 872ab26

Please sign in to comment.