如何在整个应用程序中调用db.open或db.connect时,如何共享返回的db对象?
我有一个dbconnect.js模块,如下所示:
var mongodb = require('mongodb');
var global_db = '';
// Define options. Note poolSize.
var serverOptions = {
'auto_reconnect': true,
'poolSize': 5
};
// Now create the server, passing our options.
var serv = new mongodb.Server('localhost', 27017, serverOptions);
// At this point, there is no connection made to the server.
// Create a handle to the Mongo database called 'myDB'.
var dbManager = new mongodb.Db('myDB', serv);
// NOW we initialize ALL 5 connections:
dbManager.open(function (error, db) {
// Do something with the connection.
global_db = db;
// Make sure to call db.close() when ALL connections need
// to be shut down.
db.close();
});
function getConnection()
{
return global_db;
}
exports.getConnection = getConnection;
我在我的app.js中使用这个dbconnect.js:
var http = require('http');
var db = require('./dbconnect').getConnection();
var collection = db.collection('testcollection');
console.log(db);
console.log(collection);
var server = http.createServer();
server.on('request',route);
server.listen(8000,'127.0.0.1');
console.log('Server running at http://127.0.0.1:8000');
function route(request,response)
{
var url = request.url;
var doc = {};
doc[url] = 'ok';
collection.insert(doc,{w:1},function(err,result)
{
if(err) console.log(err);
else console.log(result);
});
}
在控制台中,db和collection变量显示空值,我也尝试删除dbconnect.js中的db.close()调用但没有用,但是当我将它放在dbconnect.js文件中时,插入工作正常dbManager.open函数,我该怎么做?或者任何类似的替代方案?
答案 0 :(得分:2)
你不能这样做,因为dbManager.open(是异步方法,但你试图从模块同步获取数据。
试试这个:
在dbconnect.js
中var on_db_ready = null;
module.exports = {
db_ready:function(db_ready_callback){
on_db_ready = db_ready_callback;
//here we call callback if already have db
if (global_db) on_db_ready(global_db);
},
getConnection:getConnection
};
dbManager.open(function (error, db) {
if (on_db_ready) on_db_ready(db);
global_db= db;
})
app.js中的:
var db = require('./dbconnect').db_ready(function(db){
//Here i have my database
//or can use getConnection method
});
这不是很漂亮的方式,但是,我希望,解释你的错误