Permalink
Browse files

If an insert fails, set isNew back to false so the save operation can…

… be retried if desired.

Without this a second attempt to save tries to do an update operation on a nonexistent document. This allows one to make the slug more unique and try again on a unique index error. Responding to the actual unique index error allows us to avoid race conditions.
  • Loading branch information...
1 parent 2255075 commit 89ffb2f8c6e0483bd7697683fd0f598ab4c517c1 @boutell boutell committed with aheckmann Apr 14, 2012
Showing with 16 additions and 1 deletion.
  1. +16 −1 lib/model.js
View
@@ -263,7 +263,16 @@ Model.prototype.init = function init (doc, query, fn) {
function handleSave (promise, self) {
return tick(function handleSave (err, result) {
- if (err) return promise.error(err);
+ if (err)
+ {
+ // If the initial insert fails provide a second chance.
+ // (If we did this all the time we would break updates)
+ if (self.inserting)
+ {
+ self.isNew = true;
+ }
+ return promise.error(err);
+ }
self._storeShard();
@@ -305,9 +314,15 @@ Model.prototype.save = function save (fn) {
this.collection.insert(this.toObject({ depopulate: 1 }), options, complete);
this._reset();
this.isNew = false;
+ // Make it possible to retry the insert
+ this.inserting = true;
this.emit('isNew', false);
} else {
+ // Make sure we don't treat it as a new object on error,
+ // since it already exists
+ this.inserting = false;
+
var delta = this._delta();
this._reset();

0 comments on commit 89ffb2f

Please sign in to comment.