From 65cc00b6d408e4e03dd1a767765c14fe0529b40e Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Sun, 14 Feb 2016 08:18:18 +0100 Subject: [PATCH] createdAt kept during any kind of update --- lib/datastore.js | 8 ++++++-- test/db.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/datastore.js b/lib/datastore.js index 06238f4..1ebffcd 100755 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -590,7 +590,7 @@ Datastore.prototype._update = function (query, updateQuery, options, cb) { }); } , function () { // Perform the update - var modifiedDoc , modifications = []; + var modifiedDoc , modifications = [], createdAt; self.getCandidates(query, function (err, candidates) { if (err) { return callback(err); } @@ -601,8 +601,12 @@ Datastore.prototype._update = function (query, updateQuery, options, cb) { for (i = 0; i < candidates.length; i += 1) { if (model.match(candidates[i], query) && (multi || numReplaced === 0)) { numReplaced += 1; + if (self.timestampData) { createdAt = candidates[i].createdAt; } modifiedDoc = model.modify(candidates[i], updateQuery); - if (self.timestampData) { modifiedDoc.updatedAt = new Date(); } + if (self.timestampData) { + modifiedDoc.createdAt = createdAt; + modifiedDoc.updatedAt = new Date(); + } modifications.push({ oldDoc: candidates[i], newDoc: modifiedDoc }); } } diff --git a/test/db.test.js b/test/db.test.js index 697e6d9..a8c027b 100755 --- a/test/db.test.js +++ b/test/db.test.js @@ -1619,6 +1619,34 @@ describe('Database', function () { }); }); + it("createdAt property is unchanged and updatedAt correct after an update, even a complete document replacement", function (done) { + var d2 = new Datastore({ inMemoryOnly: true, timestampData: true }); + d2.insert({ a: 1 }); + d2.findOne({ a: 1 }, function (err, doc) { + var createdAt = doc.createdAt.getTime(); + + // Modifying update + setTimeout(function () { + d2.update({ a: 1 }, { $set: { b: 2 } }, {}); + d2.findOne({ a: 1 }, function (err, doc) { + doc.createdAt.getTime().should.equal(createdAt); + assert.isBelow(Date.now() - doc.updatedAt.getTime(), 5); + + // Complete replacement + setTimeout(function () { + d2.update({ a: 1 }, { c: 3 }, {}); + d2.findOne({ c: 3 }, function (err, doc) { + doc.createdAt.getTime().should.equal(createdAt); + assert.isBelow(Date.now() - doc.updatedAt.getTime(), 5); + + done(); + }); + }, 20); + }); + }, 20); + }); + }); + }); // ==== End of 'Update' ==== //