Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

fix isNew on sub doc after insertion error

relates to #837
  • Loading branch information...
commit a4d33f3dd2ab890357a4e491811daed9c18922b8 1 parent 89ffb2f
@aheckmann aheckmann authored
Showing with 30 additions and 7 deletions.
  1. +6 −7 lib/model.js
  2. +24 −0 test/model.test.js
View
13 lib/model.js
@@ -263,13 +263,12 @@ Model.prototype.init = function init (doc, query, fn) {
function handleSave (promise, self) {
return tick(function handleSave (err, result) {
- if (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)
- {
+ if (self._inserting) {
self.isNew = true;
+ self.emit('isNew', true);
}
return promise.error(err);
}
@@ -314,14 +313,14 @@ 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);
+ // Make it possible to retry the insert
+ this._inserting = true;
} else {
// Make sure we don't treat it as a new object on error,
// since it already exists
- this.inserting = false;
+ this._inserting = false;
var delta = this._delta();
this._reset();
View
24 test/model.test.js
@@ -5,6 +5,7 @@
var start = require('./common')
, should = require('should')
+ , assert = require('assert')
, mongoose = start.mongoose
, random = require('../lib/utils').random
, Query = require('../lib/query')
@@ -557,6 +558,29 @@ module.exports = {
});
},
+ 'isNew on parent and subdocs on failed inserts': function () {
+ var db = start()
+
+ var schema = new Schema({
+ name: { type: String, unique: true }
+ , em: [new Schema({ x: Number })]
+ }, { collection: 'testisnewonfail_'+random() });
+ var A = db.model('isNewOnFail', schema);
+ var a = new A({ name: 'i am new', em: [{ x: 1 }] });
+ a.save(function (err) {
+ should.strictEqual(null, err);
+ assert.equal(a.isNew, false);
+ assert.equal(a.em[0].isNew, false);
+ var b = new A({ name: 'i am new', em: [{x:2}] });
+ b.save(function (err) {
+ db.close();
+ assert(err);
+ assert.equal(b.isNew, true);
+ assert.equal(b.em[0].isNew, true);
+ });
+ });
+ },
+
'modified states are reset after save runs': function () {
var db = start()
, B = db.model('BlogPost', collection)
Please sign in to comment.
Something went wrong with that request. Please try again.