简体   繁体   English

MongoDb 连接初始化和查询很慢,而使用 Electron

[英]MongoDb connection initialization and query is very slow, while using Electron

First of all, i must say that i am new to Electron.首先,我必须说我是 Electron 的新手。 And I think the problem lies in Electron, because same code runs very fast without Electron (or with Electron, if first html page is used).而且我认为问题出在 Electron 上,因为没有 Electron (或使用 Electron,如果第一个 ZFC35FDC70D5FC69D526 页面使用了),相同的代码运行得非常快。 I would be appreciated, if you can help me to make database access faster in Case 2. (Additional info, software versions from package.json ==> "electron": "^9.0.5" & "mongodb": "^3.5.9" & windows 10)如果您能帮助我在案例 2 中更快地访问数据库,我将不胜感激。(附加信息,软件版本来自 package.json ==> "electron": "^9.0.5" & "mongodb": "^3.5 .9" & windows 10)

Case 1. It runs ok (it means, very fast, in milliseconds)案例 1.它运行正常(这意味着,非常快,以毫秒为单位)

Description: After instantiating a BrowserWindow with firstPage.html (renderer process) in Electron and calling the following functions in its javascript code,说明:在 Electron 中使用firstPage.html (渲染器进程)实例化 BrowserWindow 并在其 javascript 代码中调用以下函数后,

  • client.connect(...) ==> a few milliseconds client.connect(...) ==> 几毫秒
  • Querying database, eg db.find() ==> a few milliseconds查询数据库,例如 db.find() ==> 几毫秒

Case 2. It is very slow (in seconds)案例 2.非常慢(以秒为单位)

Description: I put an " a tag " (see <a href="secondPage.html"...>) in this first BrowserWindow's HTML page ( firstPage.html ) and click to this link to see another HTML page ( secondPage.html ). Description: I put an " a tag " (see <a href="secondPage.html"...>) in this first BrowserWindow's HTML page ( firstPage.html ) and click to this link to see another HTML page ( secondPage.html )。 If I click to button in secondPage.html, I realize that database access becomes very slow.如果我单击 secondPage.html 中的按钮,我意识到数据库访问变得非常缓慢。

  • client.connect(...) ==> ca. client.connect(...) ==> 大约10 seconds 10 秒
  • Querying database, eg db.find() ==> more than 10 seconds查询数据库,例如 db.find() ==> 超过 10 秒

Here is the related code:以下是相关代码:

    firstPage.html:
        <a id="idInFirstPage" class="button-link">Get Data</a> <!-- very fast db access -->
        <a href="secondPage.html">Change Page</a>
        <script src="firstPage.js"></script>

    secondPage.html:
        <a id="idInSecondPage" class="button-link">Get Data</a> <!-- very slow db access -->
        <script src="secondPage.js"></script>

    firstPage.js (the only difference to secondPage.js is the id in querySelector):
        // I searched in internet for similar problems and optimized this url connection string, 
        // i.e. i changed localhost with 127.0.0.1 and added family, but problem still persists

        const url = "mongodb://127.0.0.1:27017&family=4"; 
        const client = new MongoClient(url, { useUnifiedTopology: true,
                                          useNewUrlParser: true });
        const dbName = "myDatabase";

        // only change the #idInFirstPage to #idInSecondPage in secondPage.js
        document.querySelector("#idInFirstPage").addEventListener("click", () => 
             {
                 client.connect(function (err) {
                     assert.equal(null, err);
                     console.log("Connected successfully to server");
                     try {
                           const db = client.db(dbName);

                           findDocuments(db, () => 
                           {
                              client.close();
                           });
                     } catch (e) {
                          console.log("Something gone wrong ==> " + e);
                          client.close();
                     }
                  });
               });

        var findDocuments = function (db, callback) {
            // Get the documents collection
            var collection = db.collection("myDataProducts");
            // Find some documents
            collection.find({}).toArray((err, docs) => {
                assert.equal(err, null);

                if (typeof docs !== "undefined" && docs.length > 0) {
                    // the array is defined and has at least one element
                    console.log("Found the following documents");
                    console.log(docs);
                }
                else {
                    console.log("No element in array!");
                }
                callback(docs);
            });
        };

You are creating and connecting DB client instance every time.您每次都在创建和连接数据库客户端实例。 In this case, you are creating an instance on the first page and again on the second page.在这种情况下,您将在第一页上创建一个实例,然后在第二页上再次创建一个实例。

I'd recommend you do DB operation at your main process so that you will need only one instance and the rendered process won't face the heavy task.我建议你在你的主进程中进行数据库操作,这样你只需要一个实例,渲染的进程就不会面临繁重的任务。 Actually, the renderer is for rendering the components on chromium-browser.实际上,渲染器是用于在 chromium-browser 上渲染组件。

So you can use like this.所以你可以像这样使用。

main.js main.js

...
var MongoClient = require("mongodb").MongoClient;
var assert = require("assert");

const url = "mongodb://127.0.0.1:27017&family=4";
const client = new MongoClient(url, {
  useUnifiedTopology: true,
  useNewUrlParser: true,
});
const dbName = "yourDBName";

const readData = async () => {
     ... // you don't need to close your client instance
}

ipcMain.on('readData', async (event, arg) => {
    const data = await readData();
    event.reply('data', data);
})

...

renderer.js (your case, firstPage and secondPage) renderer.js (你的情况,firstPage 和 secondPage)

...
document.querySelector("#idInSecondPage").addEventListener("click", () => {
     ipcRenderer.send('readData', {dbName: 'products'} )
});
ipcRenderer.on('data', data => {console.log(data} )
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM