Skip to content

Commit

Permalink
Merge pull request #31 from MarkParnwell/fix/discriminator-explicit-v…
Browse files Browse the repository at this point in the history
…alue

Fix: Handle discriminators with explicit values
  • Loading branch information
vkarpov15 authored Mar 8, 2024
2 parents e86884f + a2dbd8d commit 12c00d3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,14 @@ function getSchemaForDoc(schema, res) {
}

const discriminatorValue = res[schema.discriminatorMapping.key];
const childSchema = schema.discriminators[discriminatorValue];
let childSchema = undefined;
for (const name of Object.keys(schema.discriminators)) {
const matchValue = schema.discriminators[name].discriminatorMapping.value || modelName;
if (matchValue === discriminatorValue) {
childSchema = schema.discriminators[name];
break;
}
}
return childSchema;
}

Expand Down
27 changes: 27 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,33 @@ describe('mongoose-lean-getters', function() {

assert.equal(docs[0].url, 'https://www.test.com discriminator field');
});

it('should call getters on schemas with discriminator using explicit value', async function() {
const options = { discriminatorKey: 'kind' };

const eventSchema = new mongoose.Schema({ time: Date }, options);
eventSchema.plugin(mongooseLeanGetters);
const Event = mongoose.model('Event2', eventSchema);

const ClickedLinkEvent = Event.discriminator('ClickedLink2',
new mongoose.Schema({
url: { type: String, get: v => v + ' discriminator field' }
}, options),
{
value: 'ExplicitClickedLink'
}
);

await ClickedLinkEvent.deleteMany({});
await ClickedLinkEvent.create({
url: 'https://www.test.com'
});

// Should not throw "Cannot read properties of undefined (reading 'eachPath')"
const docs = await ClickedLinkEvent.find().lean({ getters: true });

assert.equal(docs[0].url, 'https://www.test.com discriminator field');
});

it('should work on schemas with discriminators in arrays', async function() {
const options = { discriminatorKey: 'kind' };
Expand Down

0 comments on commit 12c00d3

Please sign in to comment.