Skip to content

Commit

Permalink
fix(timestamps): set timestamps on empty replaceOne()
Browse files Browse the repository at this point in the history
Re: #9951
Re: #13170
  • Loading branch information
vkarpov15 committed Mar 22, 2023
1 parent 04786ca commit 14112d6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/helpers/timestamps/setupTimestamps.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ const handleTimestampOption = require('../schema/handleTimestampOption');
const setDocumentTimestamps = require('./setDocumentTimestamps');
const symbols = require('../../schema/symbols');

const replaceOps = new Set([
'replaceOne',
'findOneAndReplace'
]);

module.exports = function setupTimestamps(schema, timestamps) {
const childHasTimestamp = schema.childSchemas.find(withTimestamp);
function withTimestamp(s) {
Expand Down Expand Up @@ -90,7 +95,7 @@ module.exports = function setupTimestamps(schema, timestamps) {
currentTime() :
this.model.base.now();
// Replacing with null update should still trigger timestamps
if (this.op === 'findOneAndReplace' && this.getUpdate() == null) {
if (replaceOps.has(this.op) && this.getUpdate() == null) {
this.setUpdate({});
}
applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),
Expand Down
13 changes: 13 additions & 0 deletions test/timestamps.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,19 @@ describe('timestamps', function() {
assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime());
});

it('sets timestamps on replaceOne (gh-9951)', async function() {
await Cat.deleteMany({});
const { _id } = await Cat.create({ name: 'notexistname' });
await Cat.replaceOne({ name: 'notexistname' }, {});
const docs = await Cat.find({});
assert.equal(docs.length, 1);
const [doc] = docs;
assert.equal(doc._id.toHexString(), _id.toHexString());
assert.ok(doc.createdAt);
assert.ok(doc.updatedAt);
assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime());
});

it('should change updatedAt when save', async function() {
const doc = await Cat.findOne({ name: 'newcat' });
const old = doc.updatedAt;
Expand Down

0 comments on commit 14112d6

Please sign in to comment.