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

docs(documents): add section on setting deeply nested properties, including warning about nullish coalescing assignment #14972

Merged
merged 1 commit into from
Oct 17, 2024

Conversation

vkarpov15
Copy link
Collaborator

@vkarpov15 vkarpov15 commented Oct 17, 2024

Fix #14944

Summary

Add section in the docs about setting deeply nested paths. Clarify that ?. and ?? are fine, we also support .get() and .set(), but ??= comes with caveats.

Examples

…luding warning about nullish coalescing assignment

Fix #14944
@vkarpov15 vkarpov15 added this to the 8.7.2 milestone Oct 17, 2024
// The following does **NOT** work.
// Do not use the following pattern with Mongoose documents.
const doc4 = new TestModel();
(doc4.nested.subdoc ??= {}).name = 'Charlie Smith';
Copy link
Collaborator

Choose a reason for hiding this comment

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

does this not work because mongoose is cloning on assignment? (i have tried in a node REPL)

ret = (doc4.nested.subdoc ??= {})
ret === doc4.nested.subdoc // eval "false"

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes. The problem is the following:

const x = {};
(doc4.nested.subdoc ??= x) === x; // true
doc4.nested.subdoc === x; // false

Basically a.b ??= x evaluates to x, not the value of a.b after the assignment. Which isn't a big deal in most cases, but with Mongoose the distinction matters.

We need to clone because doc4.nested.subdoc needs change tracking. This may be a case where using proxies instead of Object.defineProperty() for change tracking would help.

@hasezoey hasezoey added the docs This issue is due to a mistake or omission in the mongoosejs.com documentation label Oct 17, 2024
@vkarpov15 vkarpov15 merged commit 61179b4 into master Oct 17, 2024
63 checks passed
@vkarpov15 vkarpov15 deleted the vkarpov15/gh-14944 branch October 17, 2024 18:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs This issue is due to a mistake or omission in the mongoosejs.com documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Nullish coalescing assignment operator does not work as expected with mongoose.
2 participants