我一直在阅读,但仍然不清楚在整个NodeJs应用程序中共享相同数据库(MongoDb)连接的最佳方法是什么。据我所知,在应用程序启动时应该打开连接,并在模块之间重复使用。我目前认为最好的方法是,server.js
(一切从此开始的主文件)连接到数据库并创建对象变量,然后将其传递给模块。一旦连接成功,模块代码将根据需要使用此变量,并且此连接保持打开状态。例如:
var MongoClient = require('mongodb').MongoClient;
var mongo = {}; // this is passed to modules and code
MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
if (!err) {
console.log("We are connected");
// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");
console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules
} else
console.log(err);
});
var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined
然后另一个模块models/user
看起来像这样:
Users = function(app, mongo) {
Users.prototype.addUser = function() {
console.log("add user");
}
Users.prototype.getAll = function() {
return "all users " + mongo.dbUsers;
}
}
module.exports = Users;
现在我有一种可怕的感觉,认为这样做是错误的,那么这个方法是否存在明显的问题,如果有,如何改进呢?
module.exports = mongoist(connectionString);
这样懒惰地导出连接。(在 MongoDB 手册中阅读有关connectionString
的内容。) - Nil