|
|
|
@ -2,7 +2,9 @@ |
|
|
|
|
* The datastore itself |
|
|
|
|
* TODO |
|
|
|
|
* Improve serialization (for types such as Dates, handle new lines in strings) |
|
|
|
|
* Serialization and deserialization functions |
|
|
|
|
* Queue inserts, removes and updates |
|
|
|
|
* Update and removes should only modify the corresponding part of the database |
|
|
|
|
*/ |
|
|
|
|
|
|
|
|
|
var fs = require('fs') |
|
|
|
@ -180,14 +182,32 @@ Datastore.prototype.persistWholeDatabase = function (data, cb) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Update the first doc matching query |
|
|
|
|
* Update all docs matching query |
|
|
|
|
* For now, very naive implementation (recalculating the whole database) |
|
|
|
|
* @param {Object} query |
|
|
|
|
* @param {Object} newDoc Will replace the former doc |
|
|
|
|
* @param {Function} cb Optional callback, signature: err, replaced?, newDoc |
|
|
|
|
* @param {Object} newDoc Will replace the former docs |
|
|
|
|
* @param {Function} cb Optional callback, signature: err, numReplaced |
|
|
|
|
*/ |
|
|
|
|
Datastore.prototype.updateOne = function (query, newDoc, cb) { |
|
|
|
|
var callback = cb || function () {}; |
|
|
|
|
Datastore.prototype.update = function (query, newDoc, cb) { |
|
|
|
|
var callback = cb || function () {} |
|
|
|
|
, self = this |
|
|
|
|
, numReplaced = 0 |
|
|
|
|
, newData = []; |
|
|
|
|
|
|
|
|
|
self.data.forEach(function (d) { |
|
|
|
|
if (Datastore.match(d, query)) { |
|
|
|
|
numReplaced += 1; |
|
|
|
|
newData.push(newDoc); |
|
|
|
|
} else { |
|
|
|
|
newData.push(d); |
|
|
|
|
} |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
self.persistWholeDatabase(newData, function (err) { |
|
|
|
|
if (err) { return callback(err); } |
|
|
|
|
self.data = newData; |
|
|
|
|
return callback(null, numReplaced); |
|
|
|
|
}); |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -196,8 +216,12 @@ Datastore.prototype.updateOne = function (query, newDoc, cb) { |
|
|
|
|
var d = new Datastore('workspace/test.db'); |
|
|
|
|
d.loadDatabase(function (err) { |
|
|
|
|
console.log(d.data); |
|
|
|
|
d.data = [{ff: 'mec'}, {ee: 'test'}]; |
|
|
|
|
|
|
|
|
|
d.update({ yahoo: 'dailymotion' }, {yahoo: 'great' }, function (err, n) { |
|
|
|
|
console.log("--------------"); |
|
|
|
|
console.log(err); |
|
|
|
|
console.log(n); |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|