-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
Conversation
…luding warning about nullish coalescing assignment Fix #14944
// The following does **NOT** work. | ||
// Do not use the following pattern with Mongoose documents. | ||
const doc4 = new TestModel(); | ||
(doc4.nested.subdoc ??= {}).name = 'Charlie Smith'; |
There was a problem hiding this comment.
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"
There was a problem hiding this comment.
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.
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