You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<li><ahref="#updating-using-queries">Updating Using Queries</a></li>
12
13
<li><ahref="#validating">Validating</a></li>
13
14
<li><ahref="#overwriting">Overwriting</a></li>
@@ -81,6 +82,54 @@ doc.name = 'foo';
81
82
awaitdoc.save(); // Throws DocumentNotFoundError
82
83
```
83
84
85
+
## Setting Nested Properties
86
+
87
+
Mongoose documents have a `set()` function that you can use to safely set deeply nested properties.
88
+
89
+
```javascript
90
+
constschema=newSchema({
91
+
nested: {
92
+
subdoc:newSchema({
93
+
name:String
94
+
})
95
+
}
96
+
});
97
+
constTestModel=mongoose.model('Test', schema);
98
+
99
+
constdoc=newTestModel();
100
+
doc.set('nested.subdoc.name', 'John Smith');
101
+
doc.nested.subdoc.name; // 'John Smith'
102
+
```
103
+
104
+
Mongoose documents also have a `get()` function that lets you safely read deeply nested properties. `get()` lets you avoid having to explicitly check for nullish values, similar to JavaScript's [optional chaining operator `?.`](https://masteringjs.io/tutorials/fundamentals/optional-chaining-array).
105
+
106
+
```javascript
107
+
constdoc2=newTestModel();
108
+
109
+
doc2.get('nested.subdoc.name'); // undefined
110
+
doc2.nested?.subdoc?.name; // undefined
111
+
112
+
doc2.set('nested.subdoc.name', 'Will Smith');
113
+
doc2.get('nested.subdoc.name'); // 'Will Smith'
114
+
```
115
+
116
+
You can use optional chaining `?.` and nullish coalescing `??` with Mongoose documents.
117
+
However, be careful when using [nullish coalescing assignments `??=`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment) to create nested paths with Mongoose documents.
118
+
119
+
```javascript
120
+
// The following works fine
121
+
constdoc3=newTestModel();
122
+
doc3.nested.subdoc??= {};
123
+
doc3.nested.subdoc.name='John Smythe';
124
+
125
+
// The following does **NOT** work.
126
+
// Do not use the following pattern with Mongoose documents.
127
+
constdoc4=newTestModel();
128
+
(doc4.nested.subdoc??= {}).name='Charlie Smith';
129
+
doc.nested.subdoc; // Empty object
130
+
doc.nested.subdoc.name; // undefined.
131
+
```
132
+
84
133
## Updating Using Queries {#updating-using-queries}
85
134
86
135
The [`save()`](api/model.html#model_Model-save) function is generally the right
0 commit comments