Skip to content

Commit fbd63c7

Browse files
authored
Merge pull request Automattic#15207 from Automattic/vkarpov15/Automatticgh-15192
fix(document): allow setting values to undefined with set(obj) syntax with strict: false
2 parents 1020947 + fd11431 commit fbd63c7

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

lib/document.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1147,7 +1147,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
11471147
} else if (pathtype === 'nested' && valForKey == null) {
11481148
this.$set(pathName, valForKey, constructing, options);
11491149
}
1150-
} else if (valForKey !== void 0) {
1150+
} else {
11511151
this.$set(pathName, valForKey, constructing, options);
11521152
}
11531153
}

test/document.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7363,6 +7363,27 @@ describe('document', function() {
73637363
assert.strictEqual(obj.subDoc.timestamp, date);
73647364
});
73657365

7366+
it('supports setting values to undefined with strict: false (gh-15192)', async function() {
7367+
const helloSchema = new mongoose.Schema({
7368+
name: { type: String, required: true },
7369+
status: { type: Boolean, required: true },
7370+
optional: { type: Number }
7371+
}, { strict: false });
7372+
const Hello = db.model('Test', helloSchema);
7373+
7374+
const obj = new Hello({ name: 'abc', status: true, optional: 1 });
7375+
const doc = await obj.save();
7376+
7377+
doc.set({ optional: undefined });
7378+
7379+
assert.ok(doc.isModified());
7380+
7381+
await doc.save();
7382+
7383+
const { optional } = await Hello.findById(doc._id).orFail();
7384+
assert.strictEqual(optional, undefined);
7385+
});
7386+
73667387
it('handles .set() on doc array within embedded discriminator (gh-7656)', function() {
73677388
const pageElementSchema = new Schema({
73687389
type: { type: String, required: true }

0 commit comments

Comments
 (0)