|
|
|
@ -7,6 +7,8 @@ |
|
|
|
|
var dateToJSON = function () { return { $$date: this.getTime() }; } |
|
|
|
|
, originalDateToJSON = Date.prototype.toJSON |
|
|
|
|
, util = require('util') |
|
|
|
|
, _ = require('underscore') |
|
|
|
|
, modifierFunctions = {} |
|
|
|
|
; |
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -123,19 +125,42 @@ function deepCopy (obj) { |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modifierFunctions.$inc = function () {}; |
|
|
|
|
modifierFunctions.$set = function () {}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Modify a DB object according to an update query |
|
|
|
|
* For now the updateQuery only replaces the object |
|
|
|
|
*/ |
|
|
|
|
function modify (obj, updateQuery) { |
|
|
|
|
if (updateQuery._id) { throw "You cannot change a document's _id"; } |
|
|
|
|
var keys = Object.keys(updateQuery) |
|
|
|
|
, firstChars = _.map(keys, function (item) { return item[0]; }) |
|
|
|
|
, dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; }) |
|
|
|
|
, newDoc, modifiers |
|
|
|
|
; |
|
|
|
|
|
|
|
|
|
updateQuery = deepCopy(updateQuery); |
|
|
|
|
updateQuery._id = obj._id; |
|
|
|
|
if (keys.indexOf('_id') !== -1) { throw "You cannot change a document's _id"; } |
|
|
|
|
|
|
|
|
|
checkObject(updateQuery); |
|
|
|
|
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) { |
|
|
|
|
throw "You cannot mix modifiers and normal fields"; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
if (dollarFirstChars.length === 0) { |
|
|
|
|
// Simply replace the object with the update query contents
|
|
|
|
|
newDoc = deepCopy(updateQuery); |
|
|
|
|
newDoc._id = obj._id; |
|
|
|
|
} else { |
|
|
|
|
// Apply modifiers
|
|
|
|
|
modifiers = _.uniq(keys); |
|
|
|
|
modifiers.forEach(function (m) { |
|
|
|
|
if (!modifierFunctions[m]) { throw "Unknown modifier " + m; } |
|
|
|
|
}); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return updateQuery; |
|
|
|
|
// Check result is valid and return it
|
|
|
|
|
checkObject(newDoc); |
|
|
|
|
return newDoc; |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|