Skip to content

Commit

Permalink
fix(document): avoid mutating original object passed to $set() when a…
Browse files Browse the repository at this point in the history
…pplying defaults to nested properties

Fix #12102
  • Loading branch information
vkarpov15 committed Jul 20, 2022
1 parent b70a0dc commit 2262a77
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/document.js
Expand Up @@ -1149,8 +1149,8 @@ Document.prototype.$set = function $set(path, val, type, options) {
}

if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') {
$applyDefaultsToNested(path[key], prefix + key, this);
this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true }));
$applyDefaultsToNested(this.$get(prefix + key), prefix + key, this);
continue;
} else if (strict) {
// Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)
Expand Down
8 changes: 5 additions & 3 deletions test/document.test.js
Expand Up @@ -8831,7 +8831,7 @@ describe('document', function() {
assert.ok(!user.updatedAt);
});

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


const doc = await Test.create({ nested: { prop: undefined } });
const obj = { nested: { prop: undefined } };
const doc = await Test.create(obj);
assert.equal(doc.nested.prop, 'some default value');

assert.deepStrictEqual(obj, { nested: { prop: undefined } });
});

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

0 comments on commit 2262a77

Please sign in to comment.