我正在使用MongoDB 的node-mongodb-native驱动程序来编写一个网站.
我有一些关于如何管理连接的问题:
对所有请求只使用一个MongoDB连接是否足够?有任何性能问题吗?如果没有,我可以设置全局连接以在整个应用程序中使用吗?
如果没有,如果我在请求到达时打开一个新连接并在处理请求时关闭它是否合适?打开和关闭连接是否昂贵?
我应该使用全局连接池吗?我听说驱动程序有一个本机连接池.这是一个不错的选择吗?
如果我使用连接池,应该使用多少个连接?
还有其他我应该注意的事情吗?
我一直在阅读和阅读,但仍然对在整个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 …Run Code Online (Sandbox Code Playgroud)