节点mysql连接池导出

节点mysql连接池导出,mysql,node.js,electron,lokijs,Mysql,Node.js,Electron,Lokijs,我正在使用electronjs制作一个应用程序。我已经创建了一个连接池,我将在我的项目中全局使用它。用户可以选择需要连接的mysql服务器,选择的服务器配置保存在lokijs数据库中。当我们创建连接池时,我们将从lokijs数据库获得mysql连接详细信息 现在我得到了这样一个错误 未捕获的TypeError:无法读取null的属性“find” 请参阅下面的代码 var mysql = require('mysql'); var loki = require("lokijs");

我正在使用electronjs制作一个应用程序。我已经创建了一个连接池,我将在我的项目中全局使用它。用户可以选择需要连接的mysql服务器,选择的服务器配置保存在lokijs数据库中。当我们创建连接池时,我们将从lokijs数据库获得mysql连接详细信息

现在我得到了这样一个错误

未捕获的TypeError:无法读取null的属性“find”

请参阅下面的代码

   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;

在此代码后添加2-3秒的睡眠

var CurConnection = db.getCollection("CurConnection");
if (CurConnection === null) {
    CurConnection = db.addCollection("CurConnection");
}
 var rows = CurConnection.find({
    '$loki': {
        '$eq': 1
    }
  });
或在此代码之前

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

我猜
db.getCollection(“CurConnection”)数据库初始化
之前执行code>。您可以将
console.log
放在
databaseInitialize
中,然后放在
db.getCollection
之前进行测试,谢谢您的回复。我试过console.log。该消息在控制台中显示错误后显示。也就是说你说的是对的。有什么解决方法吗?你可以使用一种叫做惰性评估的方法。简单地说,创建一个函数,该函数将获取
CurConnection
,并创建db
连接,然后将该函数导出到其他模块。您还应该
将该函数货币化,这样它就不会多次创建相同的连接。