gpt4 book ai didi

javascript - 如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:36 24 4
gpt4 key购买 nike

我一直在阅读,但仍然对跨整个 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 数据库实例的功能:

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 时,它们只会被加载/获取一次,因此您最终只会得到一个 _db 实例,并且 mongoUtil.getDb() 将始终返回同一个实例。

注意,代码未经测试。

关于javascript - 如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49846202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com