【发布时间】:2018-05-13 05:40:53
【问题描述】:
我正在使用 electronjs 制作应用程序。我创建了一个连接池,我将在我的项目中全局使用它。用户可以选择他需要连接的 mysql 服务器,并且选择的服务器配置保存在 lokijs 数据库中。当我们创建连接池时,我们将从 lokijs 数据库中获取 mysql 连接详细信息。
现在我收到这样的错误。
未捕获的类型错误:无法读取属性'find' of null
请看下面的代码
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;
【问题讨论】:
-
我猜
db.getCollection("CurConnection");在databaseInitialize之前执行。您可以通过将console.log放入databaseInitialize和db.getCollection之前进行测试 -
感谢您的回复。我试过console.log。在控制台中显示错误后将显示该消息。这意味着你说的是正确的。有什么解决办法吗?
-
你使用了一种叫做惰性评估的东西。简单地说,创建一个函数来获取
CurConnection并创建dbconnection,然后将此函数导出到其他模块。你还应该monetize这个函数,这样它就不会多次创建相同的连接。
标签: mysql node.js electron lokijs