撒科打诨
下面是一些管理MongoDB连接的代码。var MongoClient = require('mongodb').MongoClient;var url = require("../config.json")["MongoDBURL"]var option = {
db:{
numberOfRetries : 5
},
server: {
auto_reconnect: true,
poolSize : 40,
socketOptions: {
connectTimeoutMS: 500
}
},
replSet: {},
mongos: {}};function MongoPool(){}var p_db;function initPool(cb){
MongoClient.connect(url, option, function(err, db) {
if (err) throw err;
p_db = db;
if(cb && typeof(cb) == 'function')
cb(p_db);
});
return MongoPool;}MongoPool.initPool = initPool;function getInstance(cb){
if(!p_db){
initPool(cb)
}
else{
if(cb && typeof(cb) == 'function')
cb(p_db);
}}MongoPool.getInstance = getInstance;module.exports = MongoPool;启动服务器时,调用initPoolrequire("mongo-pool").initPool();然后,在任何其他模块中,您可以执行以下操作:var MongoPool = require("mongo-pool");MongoPool.getInstance(function (db){
// Query your MongoDB database.});