Skip to content

Commit

Permalink
Fix return values for Model.insert
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed Dec 2, 2013
1 parent 68f41e9 commit d9483d4
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,38 +147,55 @@ Model.prototype.insert = Model.prototype.create = function (object, callback) {

var $ = this;

if(!Array.isArray(object)) object = [object];
var returnArray = true;

if(!Array.isArray(object)) {
object = [object];
returnArray = false;
}

var created = [];



var end = function(err, results) {
if(!results) return callback(err);

if(!Array.isArray(results)) results = [results];

if(returnArray) return callback(err, results);
return callback(err, results[0]);
};

var next = function(err, instance) {
if(err) return callback(err, created);
if(err) return end(err, created);
if(instance) created.push(instance);
if(object.length === 0) {
$.setupIndexes();
return callback(null, created);
return end(null, created);
}

var toInsert = object.shift();
doHook(toInsert);
};

var doInsert = function(err, object) {
var doInsert = function(err) {
if(err) return next(err);

var validation = validate($.options.schema, object);
var validation = validate($.options.schema, this);

if (!validation.passed) return next(validation.toError());

var instance = $.wrap.call($, object, true);
var instance = $.wrap.call($, this, true);
instance.save(next);
};

var doHook = function(object) {
if ($.options.hooks.beforeCreate) {
if ($.options.hooks.beforeCreate.length === 0) $.options.hooks.beforeCreate.call(object);
else return $.options.hooks.beforeCreate.call(object, doInsert);
}
if ($.options.hooks.beforeCreate.length === 0) $.options.hooks.beforeCreate.call(object);
else return $.options.hooks.beforeCreate.call(object, doInsert.bind(object));
}
doInsert.call(object);
};

next();
Expand Down

0 comments on commit d9483d4

Please sign in to comment.