Skip to content

Commit

Permalink
fix(schema+discriminator): support defining recursive embedded discri…
Browse files Browse the repository at this point in the history
…minators by passing document array schematype to discriminator

Fix #9600
  • Loading branch information
vkarpov15 committed Dec 2, 2020
1 parent 991b4fb commit 3123bec
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/schema.js
Expand Up @@ -869,6 +869,9 @@ Object.defineProperty(Schema.prototype, 'base', {

Schema.prototype.interpretAsType = function(path, obj, options) {
if (obj instanceof SchemaType) {
if (obj.path === path) {
return obj;
}
const clone = obj.clone();
clone.path = path;
return clone;
Expand Down
40 changes: 40 additions & 0 deletions test/model.discriminator.test.js
Expand Up @@ -1645,4 +1645,44 @@ describe('model', function() {
actions.discriminator('message', Message.schema);
assert.ok(actions.schema.discriminators['message']);
});

it('recursive embedded discriminator using schematype (gh-9600)', function() {
const contentSchema = new mongoose.Schema({}, { discriminatorKey: 'type' });
const nestedSchema = new mongoose.Schema({
body: {
children: [contentSchema]
}
});
const childrenArraySchema = nestedSchema.path('body.children');
childrenArraySchema.discriminator(
'container',
new mongoose.Schema({
body: { children: childrenArraySchema }
})
);
const Nested = mongoose.model('nested', nestedSchema);

const nestedDocument = new Nested({
body: {
children: [
{ type: 'container', body: { children: [] } },
{
type: 'container',
body: {
children: [
{
type: 'container',
body: {
children: [{ type: 'container', body: { children: [] } }]
}
}
]
}
}
]
}
});

assert.deepEqual(nestedDocument.body.children[1].body.children[0].body.children[0].body.children, []);
});
});

0 comments on commit 3123bec

Please sign in to comment.