Skip to content

Commit

Permalink
refactor doc#init
Browse files Browse the repository at this point in the history
  • Loading branch information
aheckmann committed Nov 4, 2011
1 parent b3808e7 commit a742c6e
Showing 1 changed file with 48 additions and 36 deletions.
84 changes: 48 additions & 36 deletions lib/document.js
Expand Up @@ -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;
};

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit a742c6e

Please sign in to comment.