diff --git a/lib/document.js b/lib/document.js index 288ec3e07d4..50d30063fe5 100644 --- a/lib/document.js +++ b/lib/document.js @@ -304,10 +304,10 @@ Document.prototype.set = function (path, val, type) { if (!pathToMark) pathToMark = path; } - if ((!schema || null === val || undefined === val) || this.try(function(){ - val = schema.applySetters(schema.cast(val, self), self); + var casted = schema.cast(val, self, false, self.get(path)); + val = schema.applySetters(casted, self); })) { if (this.isNew) { diff --git a/lib/schema/documentarray.js b/lib/schema/documentarray.js index a5f98e6c445..45f3fd16968 100644 --- a/lib/schema/documentarray.js +++ b/lib/schema/documentarray.js @@ -97,16 +97,12 @@ DocumentArray.prototype.doValidate = function (array, fn, scope) { * @api private */ -DocumentArray.prototype.cast = function (value, doc, init) { +DocumentArray.prototype.cast = function (value, doc, init, prev) { var subdoc - , cur , i if (Array.isArray(value)) { if (!(value instanceof MongooseDocumentArray)) { - // get the current MongooseArray if any before - // casting the value to prevent infinite loop. - cur = doc && doc.get(this.path); value = new MongooseDocumentArray(value, this.path, doc); } @@ -120,7 +116,7 @@ DocumentArray.prototype.cast = function (value, doc, init) { delete subdoc._doc._id; value[i] = subdoc.init(value[i]); } else { - subdoc = cur && cur.id(value[i]._id) || + subdoc = prev && prev.id(value[i]._id) || new this.caster(null, value); value[i] = subdoc.set(value[i]); } @@ -129,7 +125,7 @@ DocumentArray.prototype.cast = function (value, doc, init) { return value; } else { - return this.cast([value], doc, init); + return this.cast([value], doc, init, prev); } throw new CastError('documentarray', value);