我一直在阅读和阅读,但仍然对在整个 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;
现在我有一种可怕的感觉,这是错误的,那么这种方法是否存在任何明显的问题,如果有,如何使它变得更好?
最佳答案
您可以创建 mongoUtil.js
具有连接到 mongo 并返回 mongo db 实例的功能的模块:
const MongoClient = require( 'mongodb' ).MongoClient;
const url = "mongodb://localhost:27017";
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) {
_db = client.db('test_db');
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
要使用它,您可以在 app.js
中执行此操作。 :
var mongoUtil = require( 'mongoUtil' );
mongoUtil.connectToServer( function( err, client ) {
if (err) console.log(err);
// start the rest of your app here
} );
然后,当您需要在其他地方访问 mongo 时,例如在另一个 .js
中文件,你可以这样做:
var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();
db.collection( 'users' ).find();
这个工作的原因是在 Node 中,当模块是 require
'd,它们只会被加载/获取一次,所以你只会得到一个 _db
的实例和 mongoUtil.getDb()
将始终返回相同的实例。
注意,代码未经测试。
https://stackoverflow.com/questions/24621940/