From 4c3aa92a40cf6476092f6a8d8ac2707fe4018609 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Thu, 16 May 2013 17:33:17 +0200 Subject: [PATCH] Use query as basis for upsertion --- lib/datastore.js | 10 ++++++---- package.json | 2 +- test/db.test.js | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/datastore.js b/lib/datastore.js index 24902e8..1c5bd76 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -187,13 +187,13 @@ Datastore.prototype.persistWholeDatabase = function (data, cb) { * Update all docs matching query * For now, very naive implementation (recalculating the whole database) * @param {Object} query - * @param {Object} newDoc Will replace the former docs + * @param {Object} updateQuery * @param {Object} options Optional options * options.multi If true, can update multiple documents (defaults to false) * options.upsert If true, document is inserted if the query doesn't match anything * @param {Function} cb Optional callback, signature: err, numReplaced, upsert (set to true if the update was in fact an upsert) */ -Datastore.prototype.update = function (query, newDoc, options, cb) { +Datastore.prototype.update = function (query, updateQuery, options, cb) { var callback , self = this , numReplaced = 0 @@ -214,7 +214,9 @@ Datastore.prototype.update = function (query, newDoc, options, cb) { if (doc) { return cb(); } else { - return self.insert(model.modify({}, newDoc), function (err) { + // The upserted document is the query (since for now queries have the same structure as + // documents), modified by the updateQuery + return self.insert(model.modify(query, updateQuery), function (err) { if (err) { return callback(err); } return callback(null, 1, true); }); @@ -226,7 +228,7 @@ Datastore.prototype.update = function (query, newDoc, options, cb) { self.data.forEach(function (d) { if (Datastore.match(d, query) && (multi || numReplaced === 0)) { numReplaced += 1; - newData.push(model.modify(d, newDoc)); + newData.push(model.modify(d, updateQuery)); } else { newData.push(d); } diff --git a/package.json b/package.json index b937cb0..e3b13a4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nedb", - "version": "0.3.2", + "version": "0.3.3", "author": { "name": "tldr.io", "email": "hello@tldr.io" diff --git a/test/db.test.js b/test/db.test.js index a9a4caa..afec11c 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -474,8 +474,9 @@ describe('Database', function () { d.find({}, function (err, docs) { docs.length.should.equal(1); - Object.keys(docs[0]).length.should.equal(2); + Object.keys(docs[0]).length.should.equal(3); docs[0].hello.should.equal('world'); + docs[0].bloup.should.equal('blap'); assert.isDefined(docs[0]._id); done();