From fd1143153aaa38566cbdc6ef35a140fa8ca487d8 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 27 Jan 2025 13:38:30 -0500 Subject: [PATCH] fix(document): allow setting values to undefined with set(obj) syntax with strict: false Fix #15192 --- lib/document.js | 2 +- test/document.test.js | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/document.js b/lib/document.js index 3b02ed475a5..9554c3a811e 100644 --- a/lib/document.js +++ b/lib/document.js @@ -1147,7 +1147,7 @@ Document.prototype.$set = function $set(path, val, type, options) { } else if (pathtype === 'nested' && valForKey == null) { this.$set(pathName, valForKey, constructing, options); } - } else if (valForKey !== void 0) { + } else { this.$set(pathName, valForKey, constructing, options); } } diff --git a/test/document.test.js b/test/document.test.js index 7a2e1e607ad..63ad0a41292 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -7363,6 +7363,27 @@ describe('document', function() { assert.strictEqual(obj.subDoc.timestamp, date); }); + it('supports setting values to undefined with strict: false (gh-15192)', async function() { + const helloSchema = new mongoose.Schema({ + name: { type: String, required: true }, + status: { type: Boolean, required: true }, + optional: { type: Number } + }, { strict: false }); + const Hello = db.model('Test', helloSchema); + + const obj = new Hello({ name: 'abc', status: true, optional: 1 }); + const doc = await obj.save(); + + doc.set({ optional: undefined }); + + assert.ok(doc.isModified()); + + await doc.save(); + + const { optional } = await Hello.findById(doc._id).orFail(); + assert.strictEqual(optional, undefined); + }); + it('handles .set() on doc array within embedded discriminator (gh-7656)', function() { const pageElementSchema = new Schema({ type: { type: String, required: true }