node.js - MongoClient.connect 仅一次

标签 node.js mongodb web-scraping puppeteer

所以在下面的函数中,我总是与我的 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/

相关文章:

javascript - 我们如何监控 mongoDB 查询?

node.js - $facet 如何提高 $lookup 的性能

html - 如何在 VBA 网页抓取中从 HTML 代码中提取 <tspan> 元素

javascript - 如何在 Express 中访问 POST 表单字段

mongodb - 如何将聚合结果存储到另一个数据库中

javascript - Vuejs $emit 不会在回调时触发

python - 如何使用 Python 从列表中的项目中删除 <br> 和 </br> 标签?

python-2.7 - 使用 &lt;script&gt; 和 var 从 BeautifulSoup 中提取数据

javascript - 查询指针数组 Mongoose Node.js

node.js - 关于与 apollo-server 一起使用时如何处理 'graphql-redis-subscriptions' 身份验证的任何想法