MongoDB Node.js driver

Node.js连接MongoDB的简单实例

安装Node.js driver

  

npm install mongodb -save

 

连接

var MongodbClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/microblog';    //your db host
MongodbClient.connect(url, function (err, db) {
    console.log("Connected to correctly to server");
    //...do your CRUD job
});

 

CRUD

  CRUD的简单实例:这里主要介绍查询一个collection的所有document

  

var doFind = function (db, callback) {
    console.log("do query ...");
    var cursor = db.collection('collection-name').find(); //collection-name is whose collection you want to query.
    cursor.each(function (err, doc) {
        if(doc!=null){
            //...do your job
        } else{
            callback();//you can close mongodb here.
        }
    });
}

参考资料:https://docs.mongodb.org/getting-started/node/

posted @ 2016-03-24 17:16  ithaibo  阅读(389)  评论(0编辑  收藏  举报
请留下你的高见