我已经搜索了很多,但仍然无法找到具体的答案。我正在尝试执行以下操作:
在 mongo.js 中
var client = require('mongodb').MongoClient,
mongodb=null;
module.exports = {
connect: function(dburl, callback) {
client.connect(dburl,
function(err, db){
mongodb = db;
if(callback) { callback(); }
});
},
db: function() {
return mongodb;
},
close: function() {
mongodb.close();
}
};
在 server.js 中
mongodb = require('./mongo');
mongodb.connect('mongodb://localhost:27017/mydb', function() {
console.log('Connected to MongoDB.');
});
在 randomfile.js 中
mongodb = require('./mongo');
mongodb.db()
.collection('mycollection')
.find({someField: 'myquery'}, {}, options)
.toArray(function(err, coll) {
if (err) { throw err; }
console.log(coll);
});
当我运行 server.js 时,会形成连接,但是当我运行 randomfile.js 时,我无法获得连接。我遇到以下错误。
类型错误:无法读取未定义的属性“集合”
我做错了什么吗?
最佳答案
当您在回调结束后执行任何操作时,连接不会持续。要保留连接,请使用连接池。
var db; //global database instance
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database; //pool the connection
coll = db.collection('test');
app.listen(3000);
console.log('Listening on port 3000');
});
//No need for further calls to connect(), reuse db
//object. Export to other files if necessary.
对于较大的应用程序,更好的解决方案是模块化连接并在应用程序的所有文件中再次使用它。
关于javascript - Node.js中如何在不同文件之间共享一个数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443317/