Skip to content

Commit

Permalink
fix(schema): ensure clone() correctly gets childSchemas
Browse files Browse the repository at this point in the history
Re: #7537
  • Loading branch information
vkarpov15 committed Feb 22, 2019
1 parent 1e473c6 commit 8384231
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
20 changes: 19 additions & 1 deletion lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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
*
Expand Down
1 change: 0 additions & 1 deletion test/model.discriminator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,6 @@ describe('model', function() {
});

it('supports clone() (gh-4983)', function(done) {
console.log('-----------');
var childSchema = new Schema({
name: String
});
Expand Down
14 changes: 14 additions & 0 deletions test/schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 8384231

Please sign in to comment.