自分で作ったり提供したりするものは、まず自分自身で使ってみろろということです。自分じゃ使わないものなら人はいくらでも無責任にも無思考にもなれる。そういう投げやりな「サービス」やら「プロダクツ」なんて、だれだってイヤだ。自分が作り手と同時に利用者の立場になれば、ちゃんと使えるレベルのものを提供しようとします。

2013年10月14日月曜日

Node.jsで MongoDBにアクセスしてみる

node-mongodb-nativeドライバーを使ってNode.jsはドキュメント指向データベースMongoDBにアクセスするサンプルです。

MongoDBドライバーインストール
npm install mongodb

/**
 * MongoDB Access Sample http://mongodb.github.io/node-mongodb-native/
 */
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://192.168.11.1:27017/blog_db", function(err, db) {
    // threadsコレクションオブジェクト作成
    var threads = db.collection('threads');
    // threadsデータクリア
    threads.remove({}, function(error, result) {
        console.log("removed result=" + result);
        // 追加データ用意
        var thread = [ {
            "title" : "title-1",
            "content" : "this is thread1 \"content\"."
        }, {
            "title" : "title-2",
            "content" : "this is thread2 \"content\"."
        }, {
            "title" : "title-3",
            "content" : "this is thread3 \"content\"."
        } ];
        threads.insert(thread, function(error, result) {
            console.log("inserted count=" + result.length);
            console.log("result[0].title=" + result[0].title);
            console.log("result[1].title=" + result[1].title);
            console.log("result[2].title=" + result[2].title);

            // 件数取得
            threads.count(function(error, count) {
                console.log('all threads count=' + count);
            });

            // title-2データ取得
            threads.findOne({
                "title" : "title-2"
            }, function(error, item) {
                if (error) {
                    throw error;
                }
                console.log("findOne({title-2})=" + item.content);

                // title-2データ更新
                threads.update({
                    "title" : "title-2"
                }, {
                    $set : {
                        "content" : "thread2 new content"
                    }
                }, function(error, result) {
                    console.log("updated result=" + result);

                    // 更新したデータを取得
                    threads.findOne({
                        "title" : "title-2"
                    }, function(error, item) {
                        console.log("updated thread2 content=" + item.content);
                    });
                });
            });
        });
    });
});

0 件のコメント:

コメントを投稿

ホームページ