はじめに
前回から、
MongoDBのセットアップ
MongoDBのサイトから、
まず適当にデータファイルを置く空ディレクトリを用意してください。そこを指定してmongodを実行するだけサーバが起動します。
mongod --nojournal --noprealloc --dbpath <データディレクトリパス>
なお、
Mongooseを使ってNode.jsからMongoDBを利用
MongoDBをnodeから利用するには、
前回作成したfirstappのディレクトリで関連モジュールをインストールします。
cd firstapp npm install mongoose
として利用するモジュールをインストールします。
モデルの実装
続いてmodel.
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/firstapp');
function validator(v) {
return v.length > 0;
}
var Post = new mongoose.Schema({
text : { type: String, validate: [validator, "Empty Error"] }
, created: { type: Date, default: Date.now }
});
exports.Post = db.model('Post', Post);
まず、
投稿データをPostというモデルで定義します。Postモデルのスキーマは、
modelメソッドは、
アプリケーションの修正
前回作成したroutes/
var model = require('../model');
var Post = model.Post;
exports.index = function(req, res){
Post.find({}, function(err, items){
res.render('index', { title: 'Entry List', items: items })
});
};
exports.form = function(req, res){
res.render('form', { title: 'New Entry' })
};
exports.create = function(req, res){
var newPost = new Post(req.body);
newPost.save(function(err){
if (err) {
console.log(err);
res.redirect('back');
} else {
res.redirect('/');
}
});
};
はじめに、
ルートパスにアクセスしたときのリスト表示では、
/createに対する処理は、
動作確認
以上で実装は完了です。アプリケーションを起動して、
node app.js
ブラウザから
「New Entry」
最後にMongoDBのシェルから実際のデータを確認してみます。mongodコマンドと同じ場所にあるmongoコマンド別のプロンプトから実行してください。まずshow dbsと命令すると、
$ mongo MongoDB shell version: 2.0.6 connecting to: test > show dbs firstapp 0.078125GB local (empty) > use firstapp switched to db firstapp > show collections posts system.indexes > db.posts.find() { "text" : "最初の投稿です。", "_id" : ObjectId("4ff96c7d7f12ede516000001"), "created" : ISODate("2012-07-08T11:18:21.466Z") } { "text" : "2番目の投稿です。", "_id" : ObjectId("4ff96c8b7f12ede516000003"), "created" : ISODate("2012-07-08T11:18:35.904Z") } { "text" : "3番目の投稿です。", "_id" : ObjectId("4ff96ca37f12ede516000006"), "created" : ISODate("2012-07-08T11:18:59.385Z") }
_idというのは、
最後に
今回は、