1

I am making an app using electronjs. I have created one connection pool which i will use globally in my project. A user can select which mysql server he need to connect and the selected server configuration is saved in a lokijs database. When we create the connection pool we will get mysql connection details from the lokijs database.

Now I am getting an error like this.

Uncaught TypeError: Cannot read property 'find' of null

Please see the code below

   var mysql = require('mysql');
   var loki = require("lokijs");

var db = new loki('config/config.json', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    autosaveInterval: 1000 // save every four seconds for our example
});

function databaseInitialize() {
    // on the first load of (non-existent database), we will have no collections so we can 
    //   detect the absence of our collections and add (and configure) them now.
    var CurConnection = db.getCollection("CurConnection");
    if (CurConnection === null) {
        CurConnection = db.addCollection("CurConnection");
    }
}

var CurConnection = db.getCollection("CurConnection");
var rows = CurConnection.find({
    '$loki': {
        '$eq': 1
    }
});

var row = rows[0];

var servername = row.selservername;
var port = row.selport;
var dbname = row.seldbname;
var username = row.selusername;
var password = row.selpassword;

var connection = mysql.createPool({
    multipleStatements: true,
    host: servername,
    port: port,
    user: username,
    password: password,
    database: dbname
});

module.exports = connection;
Ayoob Khan
  • 1,536
  • 2
  • 15
  • 13
  • I guess `db.getCollection("CurConnection");` is executed before `databaseInitialize`. You can test by putting `console.log` inside `databaseInitialize ` and just before `db.getCollection` – kkkkkkk May 13 '18 at 07:42
  • thanks for the reply. I tried console.log. The message appears after errors are shown in the console. which means what you said is correct. is there any work around for this? – Ayoob Khan May 13 '18 at 08:45
  • You use use something called lazy-evaluation. Simply put, make a function which will get the `CurConnection` and create the db `connection`, then export this function to other modules. You should also `monetize` this function so that it will not create the same connection many times. – kkkkkkk May 13 '18 at 09:14

1 Answers1

1

Add sleep of 2-3 seconds after this code

var CurConnection = db.getCollection("CurConnection");
if (CurConnection === null) {
    CurConnection = db.addCollection("CurConnection");
}

or before this code

 var rows = CurConnection.find({
    '$loki': {
        '$eq': 1
    }
  });
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Santosh
  • 41
  • 4