Skip to content

Commit

Permalink
Added a Model.create shortcut for creating documents (with test).
Browse files Browse the repository at this point in the history
  • Loading branch information
bnoguchi committed Feb 1, 2011
1 parent c3efb72 commit 2adad57
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/mongoose/index.js
Expand Up @@ -326,3 +326,5 @@ exports.Promise = Promise;
*/

exports.Error = require('./error');

exports.mongo = require('../../support/node-mongodb-native/lib/mongodb');
17 changes: 17 additions & 0 deletions lib/mongoose/model.js
Expand Up @@ -506,6 +506,23 @@ Model.count = function (query, callback) {
});
};


/**
* Shortcut for creating a new Document that is automatically saved
* to the db if valid.
*
* @param {Object} doc
* @param {Function} callback
* @api public
*/
Model.create = function (doc, fn) {
var document = new this(doc);
document.save(function (err) {
if (err) fn(err)
else fn(null, document);
});
};

/**
* Updates documents.
*
Expand Down
26 changes: 26 additions & 0 deletions test/model.test.js
Expand Up @@ -146,6 +146,32 @@ module.exports = {
});
},

'test a model structures when created': function () {
var db = start()
, BlogPost = db.model('BlogPost', collection);

BlogPost.create({ title: 'hi there'}, function (err, post) {
should.strictEqual(err, null);
post.get('_id').should.be.an.instanceof(DocumentObjectId);

should.strictEqual(post.get('title'), 'hi there');
should.strictEqual(post.get('slug'), null);
should.strictEqual(post.get('date'), null);

post.get('meta').should.be.a('object');
post.get('meta').should.eql({
date: null
, visitors: null
});

should.strictEqual(post.get('published'), null);

post.get('owners').should.be.an.instanceof(MongooseArray);
post.get('comments').should.be.an.instanceof(DocumentArray);
db.close();
});
},

'test a model structure when initd': function(){
var db = start()
, BlogPost = db.model('BlogPost', collection);
Expand Down

0 comments on commit 2adad57

Please sign in to comment.