我正在开发一个提供REST api的express应用程序,它通过mongoskin使用mongodb。我想要一个能将路由从数据库访问中分离出来的层。我见过一个通过创建模块文件来创建数据库桥的示例,一个示例models/profiles.js:
var mongo = require('mongoskin'),
db = mongo.db('localhost:27017/profiler'),
profs = db.collection('profiles');
exports.examplefunction = function (info, cb) {
//code that acess the profs collection and do the query
}稍后,在路由文件中需要此模块。
我的问题是:如果我使用这种方法为每个集合创建一个模块,它是否有效?通过这样做,我会多次(不必要地)连接和断开与mongo的连接吗?
我在想,也许将db变量从一个模块导出到处理每个集合的其他模块可以解决这个问题,但我不确定。
发布于 2012-09-23 23:17:46
使用单个连接,然后创建传入共享数据库实例的模块。您希望避免为每个模块设置单独的数据库池。这样做的一种方法是将模块构造为类。
exports.build = function(db) {
return new MyClass(db);
}
var MyClass = function(db) {
this.db = db;
}
MyClass.doQuery = function() {
}https://stackoverflow.com/questions/12417425
复制相似问题