diff --git a/lib/document.js b/lib/document.js index 50d30063fe5..4348e6636e6 100644 --- a/lib/document.js +++ b/lib/document.js @@ -35,12 +35,16 @@ function Document (obj, fields) { this.schema.requiredPaths.forEach(function (path) { self._activePaths.require(path); }); + this._saveError = null; this._validationError = null; this.isNew = true; + if (obj) this.set(obj); + this._registerHooks(); this.doQueue(); + this.errors = undefined; }; @@ -156,51 +160,59 @@ Document.prototype.buildDoc = function (fields) { */ Document.prototype.init = function (doc, fn) { - var self = this; this.isNew = false; - function init (obj, doc, prefix) { - prefix = prefix || ''; + init(this, doc, this._doc); + this.emit('init'); - var keys = Object.keys(obj) - , len = keys.length - , i; + if (fn) + fn(null); - while (len--) { - i = keys[len]; - var path = prefix + i - , schema = self.schema.path(path); + return this; +}; - if (!schema && obj[i] && 'Object' === obj[i].constructor.name) { - // assume nested object - doc[i] = {}; - init(obj[i], doc[i], path + '.'); - } else { - if (obj[i] === null) { - doc[i] = null; - } else if (obj[i] !== undefined) { - if (schema) { - self.try(function(){ - doc[i] = schema.cast(obj[i], self, true); - }); - } else { - doc[i] = obj[i]; - } - } - // mark as hydrated - self._activePaths.init(path); - } - } - }; +/** + * Init helper. + * @param {Object} instance + * @param {Object} obj - raw mongodb doc + * @param {Object} doc - object we are initializing + * @private + */ - init(doc, self._doc); +function init (self, obj, doc, prefix) { + prefix = prefix || ''; - this.emit('init'); + var keys = Object.keys(obj) + , len = keys.length + , schema + , path + , i; - if (fn) - fn(null); + while (len--) { + i = keys[len]; + path = prefix + i; + schema = self.schema.path(path); - return this; + if (!schema && obj[i] && 'Object' === obj[i].constructor.name) { + // assume nested object + doc[i] = {}; + init(self, obj[i], doc[i], path + '.'); + } else { + if (obj[i] === null) { + doc[i] = null; + } else if (obj[i] !== undefined) { + if (schema) { + self.try(function(){ + doc[i] = schema.cast(obj[i], self, true); + }); + } else { + doc[i] = obj[i]; + } + } + // mark as hydrated + self._activePaths.init(path); + } + } }; // Set up middleware support