Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(schema): make Schema.prototype.clone() avoid creating different copies of subdocuments and single nested paths underneath single nested paths #13671

Merged
merged 1 commit into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 19 additions & 1 deletion lib/schema.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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