Skip to content

Commit

Permalink
Merge pull request #13427 from Automattic/IslandRhythms/gh-13379
Browse files Browse the repository at this point in the history
fix: avoid setting null property when updating doc
  • Loading branch information
vkarpov15 committed May 22, 2023
2 parents d6c2320 + 73900e1 commit 048ec48
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/helpers/update/applyTimestampsToUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,12 @@ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, optio

if (Array.isArray(updates)) {
// Update with aggregation pipeline
if (updatedAt == null) {
return updates;
}
updates.push({ $set: { [updatedAt]: now } });

return updates;
}

updates.$set = updates.$set || {};
if (!skipUpdatedAt && updatedAt &&
(!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) {
Expand Down
33 changes: 33 additions & 0 deletions test/timestamps.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,39 @@ describe('timestamps', function() {
assert.deepStrictEqual(keys, ['location', '_id', 'createdAt', 'updatedAt']);
}
});
it('should avoid setting null update when updating document with timestamps gh-13379', async function() {

const subWithTimestampSchema = new Schema({
subName: {
type: String,
default: 'anonymous',
required: true
}
});

subWithTimestampSchema.set('timestamps', true);

const testSchema = new Schema({
name: String,
sub: { type: subWithTimestampSchema }
});

const Test = db.model('gh13379', testSchema);

const doc = new Test({
name: 'Test Testerson',
sub: { subName: 'John' }
});
await doc.save();
await Test.updateMany({}, [{ $set: { updateCounter: 1 } }]);
// oddly enough, the null property is not accessible. Doing check.null doesn't return anything even though
// if you were to console.log() the output of a findOne you would be able to see it. This is the workaround.
const test = await Test.countDocuments({ null: { $exists: true } });
assert.equal(test, 0);
// now we need to make sure that the solution didn't prevent the updateCounter addition
const check = await Test.findOne();
assert(check.toString().includes('updateCounter: 1'));
});
});

async function delay(ms) {
Expand Down

0 comments on commit 048ec48

Please sign in to comment.