diff --git a/lib/helpers/document/compile.js b/lib/helpers/document/compile.js index ae91183ea34..0868f24516c 100644 --- a/lib/helpers/document/compile.js +++ b/lib/helpers/document/compile.js @@ -141,7 +141,7 @@ function defineKey(prop, subprops, prototype, prefix, keys, options) { if (v != null && v.$__isNested) { // Convert top-level to POJO, but leave subdocs hydrated so `$set` // can handle them. See gh-9293. - v = v.$__parent.get(v.$__.nestedPath); + v = v.$__parent.get(path); } const doc = this.$__[scopeSymbol] || this; doc.$set(path, v); diff --git a/test/document.test.js b/test/document.test.js index 9f106058407..864e53c63f3 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -9164,6 +9164,39 @@ describe('document', function() { }); }); + it('doesnt wipe out nested paths when setting a nested path to itself (gh-9313)', function() { + const schema = new Schema({ + nested: { + prop1: { type: Number, default: 50 }, + prop2: { + type: String, + enum: ['val1', 'val2'], + default: 'val1', + required: true + }, + prop3: { + prop4: { type: Number, default: 0 } + } + } + }); + + const Model = db.model('Test', schema); + + return co(function*() { + let doc = yield Model.create({}); + + doc = yield Model.findById(doc); + + doc.nested = doc.nested; + + assert.equal(doc.nested.prop2, 'val1'); + yield doc.save(); + + const fromDb = yield Model.collection.findOne({ _id: doc._id }); + assert.equal(fromDb.nested.prop2, 'val1'); + }); + }); + it('allows saving after setting document array to itself (gh-9266)', function() { const Model = db.model('Test', Schema({ keys: [{ _id: false, name: String }] }));