From 838423125180d80f10a75b07b601c9dd284405e7 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 22 Feb 2019 13:26:32 -0500 Subject: [PATCH] fix(schema): ensure clone() correctly gets `childSchemas` Re: #7537 --- lib/schema.js | 20 +++++++++++++++++++- test/model.discriminator.test.js | 1 - test/schema.test.js | 14 ++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/schema.js b/lib/schema.js index e500ca06ac7..361a01e0f46 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -301,12 +301,13 @@ Schema.prototype.clone = function() { s.paths = utils.clone(this.paths); s.nested = utils.clone(this.nested); s.subpaths = utils.clone(this.subpaths); - s.childSchemas = this.childSchemas.slice(); s.singleNestedPaths = utils.clone(this.singleNestedPaths); + s.childSchemas = gatherChildShemas(s); s.virtuals = utils.clone(this.virtuals); s.$globalPluginsApplied = this.$globalPluginsApplied; s.$isRootDiscriminator = this.$isRootDiscriminator; + s.$implicitlyCreated = this.$implicitlyCreated; if (this.discriminatorMapping != null) { s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); @@ -622,6 +623,23 @@ Schema.prototype.path = function(path, obj) { return this; }; +/*! + * ignore + */ + +function gatherChildShemas(schema) { + const childSchemas = []; + + for (const path of Object.keys(schema.paths)) { + const schematype = schema.paths[path]; + if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { + childSchemas.push({ schema: schematype.schema, model: schematype.caster }); + } + } + + return childSchemas; +} + /** * The Mongoose instance this schema is associated with * diff --git a/test/model.discriminator.test.js b/test/model.discriminator.test.js index 5579ed8f133..6bf99dbee01 100644 --- a/test/model.discriminator.test.js +++ b/test/model.discriminator.test.js @@ -501,7 +501,6 @@ describe('model', function() { }); it('supports clone() (gh-4983)', function(done) { - console.log('-----------'); var childSchema = new Schema({ name: String }); diff --git a/test/schema.test.js b/test/schema.test.js index a909a60bdcd..04ba2b9158a 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -1876,6 +1876,20 @@ describe('schema', function() { assert.equal(otherSchema.path('name').validators.length, 1); assert.equal(schema.path('name').validators.length, 0); }); + + it('correctly copies all child schemas (gh-7537)', function() { + const l3Schema = new Schema({ name: String }); + const l2Schema = new Schema({ l3: l3Schema }); + const l1Schema = new Schema({ l2: l2Schema }); + + assert.equal(l1Schema.childSchemas.length, 1); + assert.ok(l1Schema.childSchemas[0].schema.path('l3')); + + const otherSchema = l1Schema.clone(); + + assert.equal(otherSchema.childSchemas.length, 1); + assert.ok(otherSchema.childSchemas[0].schema.path('l3')); + }); }); it('TTL index with timestamps (gh-5656)', function(done) {