Skip to content

Commit 6d526cd

Browse files
committed
fix(document): allow setting nested path to null
Fix #14205
1 parent 8e141d1 commit 6d526cd

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

lib/document.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1153,6 +1153,8 @@ Document.prototype.$set = function $set(path, val, type, options) {
11531153
} else {
11541154
throw new StrictModeError(key);
11551155
}
1156+
} else if (pathtype === 'nested' && valForKey === null) {
1157+
this.$set(pathName, valForKey, constructing, options);
11561158
}
11571159
} else if (valForKey !== void 0) {
11581160
this.$set(pathName, valForKey, constructing, options);

test/document.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12437,6 +12437,25 @@ describe('document', function() {
1243712437
const fromDb = await Test.findById(eventObj._id).lean().orFail();
1243812438
assert.strictEqual(fromDb.__stateBeforeSuspension.field3['.ippo'], 5);
1243912439
});
12440+
12441+
it('handles setting nested path to null (gh-14205)', function() {
12442+
const schema = new mongoose.Schema({
12443+
nested: {
12444+
key1: String,
12445+
key2: String
12446+
}
12447+
});
12448+
12449+
const Model = db.model('Test', schema);
12450+
12451+
const doc = new Model();
12452+
doc.init({
12453+
nested: { key1: 'foo', key2: 'bar' }
12454+
});
12455+
12456+
doc.set({ nested: null });
12457+
assert.strictEqual(doc.toObject().nested, null);
12458+
});
1244012459
});
1244112460

1244212461
describe('Check if instance function that is supplied in schema option is availabe', function() {

0 commit comments

Comments
 (0)