Skip to content

Commit

Permalink
fix(setDefaultsOnInsert): avoid applying defaults on insert if nested…
Browse files Browse the repository at this point in the history
… property set

Fix #12279
  • Loading branch information
vkarpov15 committed Sep 4, 2022
1 parent 803a786 commit 2be0e37
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/helpers/setDefaultsOnInsert.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ function isModified(modified, path) {
if (modified[path]) {
return true;
}

// Is any parent path of `path` modified?
const sp = path.split('.');
let cur = sp[0];
for (let i = 1; i < sp.length; ++i) {
Expand All @@ -113,5 +115,13 @@ function isModified(modified, path) {
}
cur += '.' + sp[i];
}

// Is any child of `path` modified?
for (const modifiedPath of Object.keys(modified)) {
if (modifiedPath.slice(0, path.length + 1) === path + '.') {
return true;
}
}

return false;
}
21 changes: 21 additions & 0 deletions test/helpers/setDefaultsOnInsert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,25 @@ describe('setDefaultsOnInsert', function() {

assert.equal(update.$setOnInsert['time.resolved'], 42);
});

it('skips default if parent is $set (gh-12279)', function() {
const SubscriptionsConfigSchema = Schema({
hasPaidSubscription: { type: Boolean, required: true },
hasPastDueInvoice: { type: Boolean, required: true }
});

const CustomerSchema = Schema({
subscriptionsConfig: {
type: SubscriptionsConfigSchema,
required: true,
default: { hasPaidSubscription: false, hasPastDueInvoice: false }
}
});

const opts = {};
let update = { $set: { 'subscriptionsConfig.hasPaidSubscription': 100 } };
update = setDefaultsOnInsert({}, CustomerSchema, update, opts);

assert.ok(!update.$setOnInsert);
});
});

0 comments on commit 2be0e37

Please sign in to comment.