Use query as basis for upsertion

pull/2/head
Louis Chatriot 12 years ago
parent e8910bf92d
commit 4c3aa92a40
  1. 10
      lib/datastore.js
  2. 2
      package.json
  3. 3
      test/db.test.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);
}

@ -1,6 +1,6 @@
{
"name": "nedb",
"version": "0.3.2",
"version": "0.3.3",
"author": {
"name": "tldr.io",
"email": "hello@tldr.io"

@ -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();

Loading…
Cancel
Save