Skip to content

Commit

Permalink
createdAt kept during any kind of update
Browse files Browse the repository at this point in the history
  • Loading branch information
louischatriot committed Feb 14, 2016
1 parent 81f2c64 commit 65cc00b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/datastore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand All @@ -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 });
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/db.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' ==== //


Expand Down

0 comments on commit 65cc00b

Please sign in to comment.