Skip to content

Commit

Permalink
Merge pull request #13671 from Automattic/vkarpov15/gh-13626
Browse files Browse the repository at this point in the history
fix(schema): make `Schema.prototype.clone()` avoid creating different copies of subdocuments and single nested paths underneath single nested paths
  • Loading branch information
vkarpov15 committed Aug 1, 2023
2 parents 0d17ccb + d012888 commit 622fa1c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
20 changes: 19 additions & 1 deletion lib/schema.js
Expand Up @@ -409,7 +409,25 @@ Schema.prototype._clone = function _clone(Constructor) {
s.paths = utils.clone(this.paths);
s.nested = utils.clone(this.nested);
s.subpaths = utils.clone(this.subpaths);
s.singleNestedPaths = utils.clone(this.singleNestedPaths);
for (const schemaType of Object.values(s.paths)) {
if (schemaType.$isSingleNested) {
const path = schemaType.path;
for (const key of Object.keys(schemaType.schema.paths)) {
s.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key];
}
for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
s.singleNestedPaths[path + '.' + key] =
schemaType.schema.singleNestedPaths[key];
}
for (const key of Object.keys(schemaType.schema.subpaths)) {
s.singleNestedPaths[path + '.' + key] =
schemaType.schema.subpaths[key];
}
for (const key of Object.keys(schemaType.schema.nested)) {
s.singleNestedPaths[path + '.' + key] = 'nested';
}
}
}
s.childSchemas = gatherChildSchemas(s);

s.virtuals = utils.clone(this.virtuals);
Expand Down
15 changes: 15 additions & 0 deletions test/schema.test.js
Expand Up @@ -2022,6 +2022,21 @@ describe('schema', function() {
const test2 = test.clone();
assert.equal(test2.localTest(), 42);
});

it('avoids creating duplicate array constructors when cloning doc array underneath subdoc (gh-13626)', function() {
const schema = new mongoose.Schema({
config: {
type: new mongoose.Schema({
attributes: [{ value: 'Mixed' }]
})
}
}).clone();

assert.strictEqual(
schema.paths['config'].schema.paths['attributes'].Constructor,
schema.singleNestedPaths['config.attributes'].Constructor
);
});
});

it('childSchemas prop (gh-5695)', function(done) {
Expand Down

0 comments on commit 622fa1c

Please sign in to comment.