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: mongoose schema default should not mutate original object #12114

Closed
wants to merge 4 commits into from

Conversation

lpizzinidev
Copy link
Contributor

Closes #12102

@Uzlopak
Copy link
Collaborator

Uzlopak commented Jul 16, 2022

I dont like spread operator here. Use clone if you need to create an immutable operation.

Copy link
Collaborator

@Uzlopak Uzlopak left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use our internal clone method.

@lpizzinidev
Copy link
Contributor Author

@Uzlopak With utils.clone() it's failing the tests, but with Object.assign(...) is working fine.
Is it necessary to use the utils function?

@Uzlopak
Copy link
Collaborator

Uzlopak commented Jul 16, 2022

If you claim that you dont want to mutate the schema then you have to deepclone. Or else it is still mutating something.

@lpizzinidev
Copy link
Contributor Author

lpizzinidev commented Jul 16, 2022

@Uzlopak The schema should be mutated, the problem is that the current implementation is mutating the original object by adding the default nested properties.
This is why I should use the standard JS method in my opinion.
I'm not trying to make a copy of the document in my code change, I'm trying to make a copy of the object so it doesn't get mutated by the $applyDefaultsToNested call.

$applyDefaultsToNested(path[key], prefix + key, this);
this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true }));
// Create a copy of the object to avoid editing the original
const pathKey = utils.clone(path[key]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like this change, it seems unnecessarily heavy from a performance perspective. I think we'd just need to refactor and be smarter about setting defaults on the nested path without setting them on the input parameter. We'll take a look and see if we can come up with an alternative solution. I agree this is a bug, I just don't think the solution is ideal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Mongoose schema default mutating original object nested properties provided to model constructor
3 participants