doc.set() on a nested path loses a nested value read from the same document (a.b becomes undefined)
Prerequisites
- I have written a descriptive issue title
Mongoose version
9.10.2 (same result on 6.13.11, 7.8.12, 8.24.4)
Node.js version
24.13.0
MongoDB version
Not needed — reproduces without a connection (Model.hydrate() + validate()). Also reproduced with findById() + save() against MongoDB 7.0.
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
26.6.2
Issue
Scenario. A schema has a nested path a.b (a plain nested object, not a subdocument). We replace the parent a with a new object and keep b as it was, taking it from the document:
const Doc = mongoose.model('Doc', new mongoose.Schema({ a: { b: { x: Number } } }));
const doc = Doc.hydrate({ _id: new mongoose.Types.ObjectId(), a: { b: { x: 1 } } });
doc.set('a', { b: doc.a.b });
doc.a.b.toObject(); // undefined — expected { x: 1 }
await doc.validate(); // ValidationError: a.b: Cast to Object failed for value "undefined" (type undefined) at path "a.b"Expected. a.b stays { x: 1 } and the document is valid: we put back the value Mongoose returned for a.b.
Actual. a.b becomes undefined, and validate() / save() fail.
For comparison, both of these keep a.b as { x: 1 }:
doc.set('a', doc.a); // the same kind of value, passed directly
doc.set('a', { b: doc.a.b.toObject() }); // a plain copyRunnable repro (node:test): https://stackblitz.com/edit/y9fnbvpw?file=index.js
Versions checked:
| mongoose | set('a', { b: doc.a.b }) |
set('a', doc.a) |
|---|---|---|
| 5.13.23 | a.b = {}, no error |
a.b = {}, no error |
| 6.13.11, 7.8.12, 8.24.4, 9.10.2 | a.b = undefined, CastError |
works |
What we think happens (from reading the nested-path branch of Document.prototype.$set in lib/document.js): when the value itself is a document, it is converted with toObject() before the nested path is cleared, which is why set('a', doc.a) works. A document value one level deeper ({ b: doc.a.b }) is converted only when a.b itself is set — after a has already been cleared — so it reads undefined.
Question. Is this expected behavior? If it is, is toObject() the recommended way to reuse nested values from the same document? We hit this in production code that rebuilt a nested settings object from the document's current values.
Source: Automattic/mongoose