diff --git a/lib/document.js b/lib/document.js index 4b8cc160942..3bfaa16c20a 100644 --- a/lib/document.js +++ b/lib/document.js @@ -1153,6 +1153,8 @@ Document.prototype.$set = function $set(path, val, type, options) { } else { throw new StrictModeError(key); } + } else if (pathtype === 'nested' && valForKey === null) { + this.$set(pathName, valForKey, constructing, options); } } else if (valForKey !== void 0) { this.$set(pathName, valForKey, constructing, options); diff --git a/test/document.test.js b/test/document.test.js index c3443d8d489..3998343215a 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -12437,6 +12437,25 @@ describe('document', function() { const fromDb = await Test.findById(eventObj._id).lean().orFail(); assert.strictEqual(fromDb.__stateBeforeSuspension.field3['.ippo'], 5); }); + + it('handles setting nested path to null (gh-14205)', function() { + const schema = new mongoose.Schema({ + nested: { + key1: String, + key2: String + } + }); + + const Model = db.model('Test', schema); + + const doc = new Model(); + doc.init({ + nested: { key1: 'foo', key2: 'bar' } + }); + + doc.set({ nested: null }); + assert.strictEqual(doc.toObject().nested, null); + }); }); describe('Check if instance function that is supplied in schema option is availabe', function() {