diff --git a/lib/Instance.js b/lib/Instance.js index 22200b4..7051d5d 100644 --- a/lib/Instance.js +++ b/lib/Instance.js @@ -158,9 +158,7 @@ function Instance(model, doc, isNew) { if (!!isNew || Object.keys(changes).length > 0) { var runOptions = function () { - var conditions = { _id: $.id }; - - model.toSource(conditions); + var conditions = model.uniqueConditions(newDoc); model.collection.update(conditions, changes, { w: 1 }, function (err, updateCount) { if (err) return cb(err); @@ -171,8 +169,8 @@ function Instance(model, doc, isNew) { model.fromSource(updated); - newDoc = _.clone(updated); - oldDoc = _.clone(updated); + newDoc = _.cloneDeep(updated); + oldDoc = _.cloneDeep(updated); addSchemaProperties(); @@ -204,9 +202,7 @@ function Instance(model, doc, isNew) { /// A function to be called once the update is complete /// - var conditions = { _id: $.id }; - - model.toSource(conditions); + var conditions = model.uniqueConditions(oldDoc); model.collection.findOne(conditions, function (err, updated) { if (err) return cb(err); @@ -227,10 +223,8 @@ function Instance(model, doc, isNew) { /// Removes this object from the database collection /// A function to be called when the object has been removed - if (oldDoc._id) { - var conditions = { _id: $.id }; - - model.toSource(conditions); + if (!isNew) { + var conditions = model.uniqueConditions(newDoc); model.collection.remove(conditions, callback); } else { diff --git a/lib/Model.js b/lib/Model.js index c023600..d380426 100644 --- a/lib/Model.js +++ b/lib/Model.js @@ -100,6 +100,20 @@ Model.prototype.toSource = function(document) { this.preprocessors.reverse(document); }; +Model.prototype.uniqueConditions = function(document) { + /// Gets a set of MongoDB conditions which uniquely identify the given document for this model in source form/summary> + /// The document to find the unique conditions for + /// + + var testDoc = _.cloneDeep(document); + this.toSource(testDoc); + + var conditions = { + _id: testDoc[_id] + }; + return conditions; +}; + Model.prototype.wrap = function (document, isNew) { /// /// Wraps the given database object in this model's Instance wrapper