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: Handle discriminators with explicit values #31

Merged
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
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
Loading