Skip to content

Commit 2262a77

Browse files
committed
fix(document): avoid mutating original object passed to $set() when applying defaults to nested properties
Fix #12102
1 parent b70a0dc commit 2262a77

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

lib/document.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1149,8 +1149,8 @@ Document.prototype.$set = function $set(path, val, type, options) {
11491149
}
11501150

11511151
if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') {
1152-
$applyDefaultsToNested(path[key], prefix + key, this);
11531152
this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true }));
1153+
$applyDefaultsToNested(this.$get(prefix + key), prefix + key, this);
11541154
continue;
11551155
} else if (strict) {
11561156
// Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)

test/document.test.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8831,7 +8831,7 @@ describe('document', function() {
88318831
assert.ok(!user.updatedAt);
88328832
});
88338833

8834-
it('Sets default when passing undefined as value for a key in a nested subdoc (gh-9039)', async function() {
8834+
it('Sets default when passing undefined as value for a key in a nested subdoc (gh-12102) (gh-9039)', async function() {
88358835
const Test = db.model('Test', {
88368836
nested: {
88378837
prop: {
@@ -8841,9 +8841,11 @@ describe('document', function() {
88418841
}
88428842
});
88438843

8844-
8845-
const doc = await Test.create({ nested: { prop: undefined } });
8844+
const obj = { nested: { prop: undefined } };
8845+
const doc = await Test.create(obj);
88468846
assert.equal(doc.nested.prop, 'some default value');
8847+
8848+
assert.deepStrictEqual(obj, { nested: { prop: undefined } });
88478849
});
88488850

88498851
it('allows accessing $locals when initializing (gh-9098)', function() {

0 commit comments

Comments
 (0)