一段封装mongodb连接的代码

来源:互联网 发布:udp监听端口 编辑:程序博客网 时间:2024/05/17 00:58

主要目的是对客户端代码屏蔽mongodb connection,避免客户端自行打开和关闭连接

exports.doWithMongo = doWithMongo;var globalConnection;function doWithMongo(callback){    if(globalConnection){        callback(globalConnection);        return;    }    var mongoClient = require('mongodb').MongoClient;    var url = "mongodb://192.168.1.111:2222,192.168.1.111:3333,192.168.1.111:4444/planx_graph_r?replicaSet=yilos_mongo_rs&maxPoolSize=5&w=1&journal=true";    mongoClient.connect(url, function (err, db) {        globalConnection = db;        callback(globalConnection);    });}

客户端调用代码:

var mongoHelper = require("./mongoHelper");mongoHelper.doWithMongo(function(db){    db.collection("users").count(function(err, count){        console.log("there are " + count + " documents in the collection: users");    });});mongoHelper.doWithMongo(function(db){    db.collection("test").insert({hello: 'world'}, function(err, objects) {        console.log(objects);    });});mongoHelper.doWithMongo(function(db){    db.collection("enterprise", {}, function (err, collection) {        collection.count(function (err, count) {            console.log("there are " + count + " documents in the collection: " + collection.collectionName);        });    });});

上面的代码避免客户端自行打开和关闭连接,但是db还是暴露到客户端,改进以后如下:

exports.doWithMongo = operateCollection;var globalConnection;function operateCollection(collectionName, callback){    if(globalConnection){        globalConnection.collection(collectionName, {}, function (err, collection) {            callback(collection);        });        return;    }    var mongoClient = require('mongodb').MongoClient;    var url = "mongodb://192.168.1.111:2222,192.168.1.111:3333,192.168.1.111:4444/planx_graph_r?replicaSet=yilos_mongo_rs&maxPoolSize=5&w=1&journal=true";    mongoClient.connect(url, function (err, db) {        globalConnection = db;        db.collection(collectionName, {}, function (err, collection) {            callback(collection);        });    });}

客户端调用的代码:

var mongoHelper = require("./mongoHelper");mongoHelper.doWithMongo("users", function(collection){    collection.count(function (err, count) {        console.log("there are " + count + " documents in the collection: " + collection.collectionName);    });});mongoHelper.doWithMongo("test", function(collection){    collection.insert({hello: 'world'}, function(err, objects) {        console.log(objects);    });});mongoHelper.doWithMongo("enterprise", function(collection){    collection.count(function (err, count) {        console.log("there are " + count + " documents in the collection: " + collection.collectionName);    });});

这样在客户端,就完全不需要看到connection对象了

0 0
原创粉丝点击