Skip to content

Commit f37b4f2

Browse files
authored
Merge pull request #14226 from Automattic/vkarpov15/gh-14205
fix(document): allow setting nested path to `null`
2 parents 8e141d1 + b286b02 commit f37b4f2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-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: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12437,6 +12437,44 @@ 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+
});
12459+
12460+
it('handles setting nested path to undefined (gh-14205)', function() {
12461+
const schema = new mongoose.Schema({
12462+
nested: {
12463+
key1: String,
12464+
key2: String
12465+
}
12466+
});
12467+
12468+
const Model = db.model('Test', schema);
12469+
12470+
const doc = new Model();
12471+
doc.init({
12472+
nested: { key1: 'foo', key2: 'bar' }
12473+
});
12474+
12475+
doc.set({ nested: void 0 });
12476+
assert.strictEqual(doc.toObject().nested, void 0);
12477+
});
1244012478
});
1244112479

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

0 commit comments

Comments
 (0)