我一直在阅读和阅读,但仍然对跨整个 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
具有连接到 mongodb 并返回 mongodb 实例的功能的模块:
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();
这样做的原因是在节点中,当模块require
d,它们只被加载/获取一次,所以你最终只会得到一个实例_db
and mongoUtil.getDb()
将始终返回相同的实例。
请注意,代码未经测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)