所以在下面的函数中,我总是与我的 mongodb 建立新的连接。我将如何更改我的代码,以便它只在开始时连接一次,而不是在所有这些功能中连接一次。
function getData(callback){
arrayOfArticles = [];
MongoClient.connect(url, { useNewUrlParser: true }, callback, function(err, db) {
if (err) throw err;
let dbo = db.db('testdb');
article = dbo.collection('testname').find({}).toArray(function(err, article) {
if (err) throw err;
db.close();
for (var i = 0, len = article.length; i < len; i++){
arrayOfArticles.push(article[i].name);
}
callback(null, arrayOfArticles);
});
});
function getPrice(callback){
arrayOfPrices = [];
MongoClient.connect(url, { useNewUrlParser: true }, callback, function(err, db) {
if (err) throw err;
let dbo = db.db('testdb');
article = dbo.collection('testcollection').find({}).toArray(function(err, arrayOfPrices) {
if (err) throw err;
db.close();
callback(null, arrayOfPrices);
});
});
function getDealerData(callback){
dealerData = [];
MongoClient.connect(url, { useNewUrlParser: true }, callback, function(err, db) {
if (err) throw err;
let dbo = db.db('Dealer');
article = dbo.collection('Dealer').find({}).toArray(function(err, dealerData) {
if (err) throw err;
db.close();
callback(null, dealerData);
});
});
最佳答案
为每个任务创建连接并不是一个好习惯。
我建议创建一个单独的文件来创建连接并在任何地方使用连接
例子
//db.js
MongoClient.connect(url, {
useNewUrlParser: true
}, callback, function (err, db) {
if (err) throw err;
global.dbo = db.db('testdb');
});
在你的主服务器文件中,我假设 app.js
并要求它在所有中间件的顶部
//app.js
<--All depandent module -->
require('db.js'); // change the path according to your structure.
现在 dbo
将可用于您所有的应用程序,并且可以在任何地方使用它。
It's also good practice to use single connection and for load, Mongo itself creates pull to handle the concurrency
As per Mongo official comment:
You open do
MongoClient.connect
once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool. So open it once an reuse across all requests.
更新
我已经尝试在这里实现你的一个功能
function getPrice(callback){
arrayOfPrices = [];
dbo.collection('testcollection').find({}).toArray(function(err, arrayOfPrices) {
if (err) throw err;
callback(null, arrayOfPrices);
});
}
关于node.js - MongoClient.connect 仅一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841529/