Skip to content

Commit

Permalink
Model.create accepts an array
Browse files Browse the repository at this point in the history
  • Loading branch information
aheckmann committed Oct 13, 2011
1 parent 5834db2 commit 15a5818
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 10 deletions.
33 changes: 23 additions & 10 deletions lib/model.js
Expand Up @@ -795,26 +795,39 @@ Model.$where = function $where () {
*/

Model.create = function create (doc, fn) {
var args = utils.args(arguments)
, lastArg = args[args.length-1]
, docs = []
, count;
if (1 === arguments.length) {
return 'function' === typeof doc && doc(null);
}

var self = this
, docs = [null]
, promise
, count
, args

if (typeof lastArg === 'function') {
fn = args.pop();
if (Array.isArray(doc)) {
args = doc;
} else {
args = utils.args(arguments, 0, arguments.length - 1);
fn = arguments[arguments.length - 1];
}

if (0 === args.length) return fn(null);

promise = new Promise(fn);
count = args.length;
var self = this;

args.forEach(function (arg, i) {
var doc = new self(arg);
docs[i] = doc;
docs[i+1] = doc;
doc.save(function (err) {
if (err) return fn(err);
--count || fn.apply(null, [null].concat(docs));
if (err) return promise.error(err);
--count || fn.apply(null, docs);
});
});

// TODO
// utilize collection.insertAll for batch processing
};

/**
Expand Down
38 changes: 38 additions & 0 deletions test/model.test.js
Expand Up @@ -4326,6 +4326,44 @@ module.exports = {
});
},

'Model.create can accept an array': function () {
var db = start()
, BlogPost = db.model('BlogPost', collection);

BlogPost.create([{ title: 'hi'}, { title: 'bye'}], function (err, post1, post2) {
db.close();
should.strictEqual(err, null);
post1.get('_id').should.be.an.instanceof(DocumentObjectId);
post2.get('_id').should.be.an.instanceof(DocumentObjectId);

post1.title.should.equal('hi');
post2.title.should.equal('bye');
});
},

'Model.create when passed no docs still fires callback': function () {
var db = start()
, BlogPost = db.model('BlogPost', collection);

BlogPost.create(function (err, a) {
db.close();
should.strictEqual(err, null);
should.not.exist(a);
});
},

'Model.create fires callback when an empty array is passed': function () {
var db = start()
, BlogPost = db.model('BlogPost', collection);

BlogPost.create([], function (err, a) {
db.close();
should.strictEqual(err, null);
should.not.exist(a);
});
},


'date casting test (gh-502)': function () {
var db = start()

Expand Down

0 comments on commit 15a5818

Please sign in to comment.