From f91a41b5341e89a8a0374abf4170ab30c51b1e6e Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Sat, 4 May 2013 18:18:13 +0200 Subject: [PATCH] DB state shouldn't be modified when the returned objects are modified --- lib/datastore.js | 4 ++-- test/db.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/datastore.js b/lib/datastore.js index 2af3da3..64e2865 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -129,7 +129,7 @@ Datastore.prototype.find = function (query, callback) { for (i = 0; i < self.data.length; i += 1) { if (Datastore.match(self.data[i], query)) { - res.push(self.data[i]); + res.push(model.deepCopy(self.data[i])); } } @@ -148,7 +148,7 @@ Datastore.prototype.findOne = function (query, callback) { for (i = 0; i < self.data.length; i += 1) { if (Datastore.match(self.data[i], query)) { - return callback(null, self.data[i]); + return callback(null, model.deepCopy(self.data[i])); } } diff --git a/test/db.test.js b/test/db.test.js index 2606998..055d6a0 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -108,6 +108,30 @@ describe('Database', function () { }); }); + it('If an object returned from the DB is modified and refetched, the original value should be found', function (done) { + d.insert({ a: 'something' }, function () { + d.findOne({}, function (err, doc) { + doc.a.should.equal('something'); + doc.a = 'another thing'; + doc.a.should.equal('another thing'); + + // Re-fetching with findOne should yield the persisted value + d.findOne({}, function (err, doc) { + doc.a.should.equal('something'); + doc.a = 'another thing'; + doc.a.should.equal('another thing'); + + // Re-fetching with find should yield the persisted value + d.find({}, function (err, docs) { + docs[0].a.should.equal('something'); + + done(); + }); + }); + }); + }); + }); + }); // ==== End of 'Insert' ==== //