ページ

2013-01-27

node.jsからMongoDBを使う


ちょっとnode.jsで作りたいものがあって、せっかくなのでDBはMongoDBを使おうという魂胆。


MongoDBは以下のように起動するとフォアグラウンドで起動してログをダラダラと見れて良い。
mongod --nojournal --noprealloc --dbpath path_to_db
path_to_dbはDBの保存先なので、開発用に適当に指定すれば良い。
他のオプションはmongodが勝手に色々ヤルのを防ぐ為で、検証用ならいいけど実運用では指定しないほうが良い類のもの。

node.jsからMongoDBをアクセスするにはnode-mongodb-nativeという公式のドライバがあるが、Introduction見ただけでネストが深くてヤバそうなのでmongooseというORMみたいなのを使う。

コードは下の通りで、実行した結果も下に貼っておく。
一回検索→何も見つからない→適当にデータ入れる→再び検索→データ見つかる(゚∀゚)
的な流れ。


// npm install mongoose
// mongod --nojournal --noprealloc --dbpath path_to_db
// node model.js
var async = require('async');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/dbname');
var Schema = mongoose.Schema;
var Word = new Schema({
text : String
,reading : String
,createdAt : {type: Date, default: Date.now}
});
var WordModel = mongoose.model("Word",Word);
var hoge = new WordModel({text:"hoge", reading:"ほげ"});
var huga = new WordModel({text:"huga", reading:"ふが"});
var saveModel = function(model, fn) {
model.save(fn);
}
var findHoge = function(fn) {
WordModel.find({text:"hoge"},fn);
}
async.series(
[
function(callback) {
findHoge(callback);
},
function(callback) {
saveModel(hoge, callback);
},
function(callback) {
saveModel(huga, callback);
},
function(callback) {
findHoge(callback);
}
],
function(err, results){
if(err){
console.log("error => " + err)
}else{
console.log("The first search results.");
console.log(results[0].length + "s results.")
console.log(results[0]);
console.log();
console.log("insert => " + results[1]);
console.log("insert => " + results[2]);
console.log();
console.log("Results after insertion.");
console.log(results[3].length + "s results.")
console.log(results[3]);
}
mongoose.disconnect();
}
);
The first search results.
0s results.
[]
insert => { __v: 0,
text: 'hoge',
reading: 'ほげ',
_id: 5104b17a8b6656c435000001,
createdAt: Sun, 27 Jan 2013 04:47:54 GMT },1
insert => { __v: 0,
text: 'huga',
reading: 'ふが',
_id: 5104b17a8b6656c435000002,
createdAt: Sun, 27 Jan 2013 04:47:54 GMT },1
Results after insertion.
1s results.
[ { text: 'hoge',
reading: 'ほげ',
_id: 5104b17a8b6656c435000001,
__v: 0,
createdAt: Sun, 27 Jan 2013 04:47:54 GMT } ]
view raw result.txt hosted with ❤ by GitHub

mongooseの使い方よりもasynモジュールの使い方にハマってそっちの方が時間掛かったのはナイショの話。

簡単に使えたので良かった。後で大量のデータ入れたりして色々試してみる予定です。

0 件のコメント:

コメントを投稿