perf(schema): clear childSchemas when overwriting existing path to avoid performance degradations #15256
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix #15253
Summary
Currently, overwriting an existing recursive path using
Schema.prototype.path()
leads to an exponential performance blowup because we're adding a separate recursive path tochildSchemas
on everypath()
call. For example, in the test case added, the document has 1092 subdocuments, but with 2 duplicatechildSchemas
entry Mongoose thinks there's over 56k subdocuments. With 3, Mongoose thinks there's about 560k subdocuments. I haven't been able to figure out a more complete explanation of the exact mathematical model of this growth, but suffice to say cleaning up duplicate childSchemas fixes the issue.Examples