-
-
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
Nullish coalescing assignment operator does not work as expected with mongoose. #14944
Comments
The same issue can also be observed for the other coalescing assignment operators Logical OR and Logical AND. |
Looks like this affects subdocs, not nested paths. const mongoose = require('mongoose');
const { Schema } = mongoose;
const schema = new Schema({
nested: {
a: Number
},
subdoc: new Schema({ b: Number })
});
const Model = mongoose.model('Test', schema);
const doc = new Model();
(doc.nested ??= {}).a = 5;
(doc.subdoc ??= {}).b = 6;
console.log(doc.nested.a); // 5
console.log(doc.subdoc.b); // undefined
console.log(doc.subdoc); // Only _id We're investigating why this is happening |
We're going to have to add this to our docs. The issue is that, if The preferred way to do this sort of safe property assignment in Mongoose is |
…luding warning about nullish coalescing assignment Fix #14944
docs(documents): add section on setting deeply nested properties, including warning about nullish coalescing assignment
Prerequisites
Mongoose version
7.2.2
Node.js version
16.20.2
MongoDB server version
7.0.2
Typescript version (if applicable)
5.5.4
Description
When setting a field in an optional subdocument via nullish coalescing assignment, the incoming value is not set on the subdocument.
Usually, the nullish coalescing operator allows for patterns like this:
However, this does not work when used with a mongoose document:
The reason is the fact that mongoose wraps the 'drive-by' assignment of
subdocument
in aSingleNested
object. Nullish coalescing assignment returns the right hand operand if the left hand operand isnullish
. Setting a field on that object (POJO) will not be picked up by mongoose, becausedoc.nested
does not reference the POJO but rather the new object mongoose created under the hood.Steps to Reproduce
The issue becomes even more apparent when looked at without the property assignment:
Expected Behavior
This is somewhat of an edge case as the nullish coalescing assignment operator might be considered quite exotic.
However, it's a big gotcha for people who don't know that mongoose routinely wraps and transforms objects under the hood.
Mongoose should not change how js operators function.
At the very least, the documentation should explicitly point out the behaviour.
The text was updated successfully, but these errors were encountered: