Skip to content

Commit

Permalink
Improved instance condition selection behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed Dec 13, 2013
1 parent b40ce22 commit c7dff1f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
18 changes: 6 additions & 12 deletions lib/Instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();

Expand Down Expand Up @@ -204,9 +202,7 @@ function Instance(model, doc, isNew) {
/// <param name="callback" type="Function">A function to be called once the update is complete</param>
/// </signature>

var conditions = { _id: $.id };

model.toSource(conditions);
var conditions = model.uniqueConditions(oldDoc);

model.collection.findOne(conditions, function (err, updated) {
if (err) return cb(err);
Expand All @@ -227,10 +223,8 @@ function Instance(model, doc, isNew) {
/// <summary>Removes this object from the database collection</summary>
/// <param name="callback" type="Function">A function to be called when the object has been removed</param>

if (oldDoc._id) {
var conditions = { _id: $.id };

model.toSource(conditions);
if (!isNew) {
var conditions = model.uniqueConditions(newDoc);

model.collection.remove(conditions, callback);
} else {
Expand Down
14 changes: 14 additions & 0 deletions lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,20 @@ Model.prototype.toSource = function(document) {
this.preprocessors.reverse(document);
};

Model.prototype.uniqueConditions = function(document) {
/// <summary>Gets a set of MongoDB conditions which uniquely identify the given document for this model in source form/summary>
/// <param name="document" type="Object">The document to find the unique conditions for</param>
/// <returns type="Object"/>

var testDoc = _.cloneDeep(document);
this.toSource(testDoc);

var conditions = {
_id: testDoc[_id]
};
return conditions;
};

Model.prototype.wrap = function (document, isNew) {
/// <signature>
/// <summary>Wraps the given database object in this model's Instance wrapper</summary>
Expand Down

0 comments on commit c7dff1f

Please sign in to comment.