简体   繁体   中英

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

First of all, i must say that i am new to 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). 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)

Case 1. It runs ok (it means, very fast, in milliseconds)

Description: After instantiating a BrowserWindow with firstPage.html (renderer process) in Electron and calling the following functions in its javascript code,

  • client.connect(...) ==> a few milliseconds
  • Querying database, eg db.find() ==> a few milliseconds

Case 2. It is very slow (in seconds)

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.

  • client.connect(...) ==> ca. 10 seconds
  • Querying database, eg db.find() ==> more than 10 seconds

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.

So you can use like this.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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