Permalink
Browse files

Model.create accepts an array

  • Loading branch information...
1 parent 5834db2 commit 15a581853d0ee965ad00cf2211ae6b1d113ce592 @aheckmann aheckmann committed Oct 13, 2011
Showing with 61 additions and 10 deletions.
  1. +23 −10 lib/model.js
  2. +38 −0 test/model.test.js
View
@@ -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
};
/**
View
@@ -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()

0 comments on commit 15a5818

Please sign in to comment.