diff --git a/lib/schema.js b/lib/schema.js index 2dabeb61404..1dd9d9e704c 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -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; diff --git a/test/model.discriminator.test.js b/test/model.discriminator.test.js index ad37c1ee187..02b46d5ac7f 100644 --- a/test/model.discriminator.test.js +++ b/test/model.discriminator.test.js @@ -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, []); + }); });