简体   繁体   English

如何在Node JS中的不同文件之间共享一个数据库连接?

[英]How to share one database connection across different files in node js?

I have searched a lot but still wasn't able to find a specific ans. 我进行了很多搜索,但仍然找不到特定的答案。 I am trying to do following: 我正在尝试执行以下操作:

In mongo.js 在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();
 }
};

In server.js 在server.js中

mongodb = require('./mongo');
mongodb.connect('mongodb://localhost:27017/mydb', function() {
 console.log('Connected to MongoDB.');
});

In randomfile.js 在randomfile.js中

 mongodb = require('./mongo');
 mongodb.db()
.collection('mycollection')
.find({someField: 'myquery'}, {}, options)
.toArray(function(err, coll) {
    if (err) { throw err; }
    console.log(coll);
});

When I run server.js a connection is formed but when I run randomfile.js I am not able to get the connection. 当我运行server.js时,会形成一个连接,但是当我运行randomfile.js时,我将无法获得连接。 I encounter following error. 我遇到以下错误。

TypeError: Cannot read property 'collection' of undefined TypeError:无法读取未定义的属性“ collection”

Am I doing something wrong? 难道我做错了什么?

When you do anything after the callback gets over, the connection does not persist. 在回调结束后执行任何操作时,连接不会持久。 To preserve the connection, use connection pooling . 要保留连接,请使用连接池

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.

More info. 更多信息。

For a larger application, a better solution would be to modularize the connection and use it again across all the files of the app. 对于较大的应用程序,更好的解决方案是模块化连接,然后在应用程序的所有文件中再次使用该连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM