在mongo-db本机客户端的数据库连接

我有一个express / nodeJs应用程序,它将在Mongo-db中使用mongo-db本地客户端来保持持久性。 现在我的问题是,我看到的大部分示例都有一个集合,因此在该js文件中进行连接,就像本教程 (在mongo-db本地客户端文档中提到的那样)。 那里的连接代码是这样的:

var Db = require('mongodb').Db; var Connection = require('mongodb').Connection; var Server = require('mongodb').Server; var BSON = require('mongodb').BSON; var ObjectID = require('mongodb').ObjectID; ArticleProvider = function(host, port) { this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {})); this.db.open(function(){}); }; ArticleProvider.prototype.getCollection= function(callback) { this.db.collection('articles', function(error, article_collection) { if( error ) callback(error); else callback(null, article_collection); }); }; ArticleProvider.prototype.findAll = function(callback) { this.getCollection(function(error, article_collection) { if( error ) callback(error) else { article_collection.find().toArray(function(error, results) { if( error ) callback(error) else callback(null, results) }); } }); }; 

还有其他的方法,我保持它保持小(检查完整教程的上述url)。

我的问题是我有更多的集合,因此我担心如何build立一个单一的连接到数据库,并将其用于所有的集合。 我也想如果你可以指定如何连接到副本集还为读取和主数据库写入。

或者我应该打电话给每个我的collection.js文件中的连接,就像上面提到的教程已经完成了一样。 请帮帮我。

尝试使用单例模式 :

在你的主要快递app.js连接到数据库并创build数据库实例:

 var Database = require('database.js'); ... mongodb.connect(config.dbAddress, function (err, db) { if(err) { return console.log('Error connection to DB'); } Database.setDB(db); app.listen(config.appPort); }); 

然后在任何其他文件中,您需要再次使用数据库require database.js:

 var Database = require('database.js'); ... ArticleProvider = function() { this.db = Database.getDB(); }; ... 

最后, database.js文件遵循单例模式:

 /** Database Singleton Object database.js is used throughout the app to access the db object. Using mongodb native drivers the db object contains a pool of connections that are used to make requests to the db. To use this singleton object simply require it and either call getDB() or setDB(). The idea is to use setDB in app.js just after we connect to the db and receive the db object, then in any other file we need the db require and call getDB **/ var mongodb = require('mongodb'); var singleton = (function() { var instance; //Singleton Instance function init() { var _db; //Instance db object (private) //Other private variables and function can be declared here return { //Gets the instance's db object getDB: function() { return _db; }, //Sets the instance's db object setDB: function(db) { _db = db; } //Other public variables and methods can be declared here }; } return { //getInstance returns the singleton instance or creates a new one if //not present getInstance: function() { if (!instance) { instance = init(); } return instance; } }; })(); module.exports = singleton.getInstance();