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

2013年10月14日月曜日

MongoSkin基本使用

MongoDBにアクセスできるドライバーMongoskinの基本使い方です。

/**
 * Mongoskin
 * https://github.com/kissjs/node-mongoskin
 * http://www.hacksparrow.com/mongoskin-tutorial-with-examples.html
 */
// ライブラリ参照
var mongo = require('mongoskin');
// DB接続
var db = mongo.db('192.168.11.1:27017/blog_db', {
    safe : false
});
// コレクション取得
var users = db.collection('users');
// user検索
users.find({
    "name" : {
        $regex : /user-[0-4]/i
    }
}).toArray(function(error, band) {
    for ( var i = 0; i < band.length; i++) {
        console.log("name" + i + "=" + band[i].name);
    }
});
var threads = db.collection('threads');
var thread = {
    "title" : "title-4",
    "content" : "this is title-4 content."
};
// データ追加
threads.insert(thread, function(error, resultArray) {
    console.log("inserted thread title=" + JSON.stringify(resultArray));
    threads.find({}).each(function(error, thread) {
        if (thread !== null)
            console.log("thread title=" + thread.title);
    });
    // データ更新
    threads.update({
        "title" : "title-4"
    }, {
        $set : {
            "content" : "new title-4 content."
        }
    }, function(error, result) {
        console.log("object is updated.");
        threads.findOne({
            "title" : "title-4"
        }, function(error, thread) {
            console.log("thread4 new content=" + thread.content);
        });
    });
});
// データ削除
threads.remove({
    "title" : "title-4"
}, function(error, result) {
    console.log("object is removed.");
});
// データ件数取得
threads.count({}, function(error, count) {
    console.log("threads.count=" + count);
});

0 件のコメント:

コメントを投稿

ホームページ