我有一个express/nodeJs应用程序,它将使用Mongo-db本地客户端用于在mongo-db中的持久性。现在我的问题是,我看到的大多数示例都有一个集合,因此在那个js文件中进行连接,就像这个tutorial(在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以获取完整的教程)。
我的问题是我有更多的集合,因此我担心如何建立到数据库的单一连接,并将其用于所有集合。我还希望您能指定如何连接到副本集,也用于读取和主数据库的写入。
或者我应该调用我的每个collection.js文件中的连接,像上面提到的教程在一个文件中完成的那样。请帮帮我。
发布于 2013-10-21 08:45:57
在主express app.js中,连接到数据库并创建数据库实例:
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);
});
然后,在任何其他文件中,您需要使用数据库,再次需要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();
https://stackoverflow.com/questions/17420621
复制相似问题