Skip to content

Commit

Permalink
Merge pull request #28 from nathan-knight/master
Browse files Browse the repository at this point in the history
fix: correctly get schema for each element of a discriminated array
  • Loading branch information
vkarpov15 authored Mar 8, 2024
2 parents 6b9b6eb + bca9df7 commit e86884f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
11 changes: 7 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function applyGetters(schema, res, path) {
}

function getSchemaForDoc(schema, res) {
if (!schema.discriminatorMapping || !schema.discriminatorMapping.key) {
if (!schema.discriminatorMapping || !schema.discriminatorMapping.key || !schema.discriminators) {
return schema;
}

Expand All @@ -81,15 +81,18 @@ function applyGettersToDoc(schema, doc, fields, prefix) {
return;
}

const schemaForDoc = getSchemaForDoc(schema, doc);

if (Array.isArray(doc)) {
for (let i = 0; i < doc.length; ++i) {
applyGettersToDoc.call(this, schemaForDoc, doc[i], fields, prefix);
const currentDoc = doc[i];
if (currentDoc == null) continue;
const schemaForDoc = getSchemaForDoc(schema, currentDoc);
applyGettersToDoc.call(this, schemaForDoc, currentDoc, fields, prefix);
}
return;
}

const schemaForDoc = getSchemaForDoc(schema, doc);

schemaForDoc.eachPath((path, schematype) => {
const pathWithPrefix = prefix ? prefix + '.' + path : path;
if (this.selectedInclusively() &&
Expand Down
28 changes: 28 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,34 @@ describe('mongoose-lean-getters', function() {
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' };

const eventSchema = new mongoose.Schema({ time: Date }, options);
const clickedLinkSchema = new mongoose.Schema({
url: { type: String, get: v => v + ' discriminator field' }
});
eventSchema.discriminator('ClickedLink', clickedLinkSchema);

const eventListSchema = new mongoose.Schema({
events: [eventSchema],
});
eventListSchema.plugin(mongooseLeanGetters);
const EventList = mongoose.model('EventList', eventListSchema);

await EventList.deleteMany({});
await EventList.create({
events: [{
kind: 'ClickedLink',
url: 'https://www.test.com'
}],
});

const docs = await EventList.find().lean({ getters: true });

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

it('should call getters on arrays (gh-30)', async function() {
function upper(value) {
return value.toUpperCase();
Expand Down

0 comments on commit e86884f

Please sign in to comment.