[英]Export MySQL connection for use with other modules in Node/Express using promise-mysql?
Attempting to import and use a database module in one of my controllers. 尝试在我的一个控制器中导入和使用数据库模块。 The initial connection is logged, however, I'm receiving the following error when hitting any of my routes from the browser: 初始连接已记录,但是,从浏览器命中任何路由时,我收到以下错误:
"Cannot read property 'query' of undefined" “无法读取未定义的属性'查询'”
The connection variable in the database.js file is obviously not being set, but for the life of me I cannot figure out why. 显然没有设置database.js文件中的连接变量,但是对于我来说,我不知道为什么。
database.js database.js
const mysql = require("promise-mysql");
const config = require("../config");
let connection;
mysql.createConnection(config.MYSQL)
.then(conn => {
connection = conn
console.log('Connected to ', config.MYSQL.database)
})
.catch(function (error) {
console.log(error)
})
module.exports = connection;
schools.js schools.js
const router = require('express').Router()
const Schools = require('../controllers/schools-controller')
const schools = new Schools
router.get('/', schools.getAllSchools)
...
module.exports = router
schools-controller.js 学校,controller.js
const db = require("../lib/database");
module.exports = class Schools {
async getAllSchools (req, res, next) {
const queryString = 'SELECT * FROM schools ORDER BY school_id ASC LIMIT 5'
try {
const results = await db.query(queryString);
if (results == "") {
res.status(404).json({ message: "No schools found" });
} else {
res.status(200).json(results);
}
} catch(error) {
next(error)
}
};
...
}
Below is the pool function I ended up using based on the answer from @Sven 以下是我根据@Sven的答案最终使用的池功能
database.js database.js
const pool = mysql.createPool(config.MYSQL);
pool.getConnection()
.then(function(connection) {
console.log(`Connected to database: ${config.MYSQL.database}`);
pool.releaseConnection(connection)
})
.catch(function(error) {
console.error(error.message);
});
module.exports = pool;
You can't export a value that is acquired asynchronously like that. 您不能导出以这种方式异步获取的值。 Just like everywhere else in Node, you have to use a callback, a promise or an async function. 就像Node中的其他地方一样,您必须使用回调,promise或async函数。 However, since this is for a MySQL connection, you should use a connection pool . 但是,由于这是针对MySQL连接的,因此您应该使用连接池 。
In your database.js
-file: 在您的database.js
-file中:
const mysql = require("promise-mysql");
const config = require("../config");
module.exports = mysql.createPool(config.MYSQL);
You need no code changes at all in the rest of your code. 在其余的代码中,您根本不需要更改任何代码。
Alternatively, you can use mysql2
instead of promise-mysql
(based on mysql
) as it offers many welcome features, listed in their readme . 另外,您可以使用mysql2
代替promise-mysql
(基于mysql
),因为它提供了许多自述文件中列出的受欢迎功能。
Your code would require very little changes, an npm i -S mysql2
or yarn add mysql2
, followed by changing the line require("promise-mysql")
to require("mysql2/promise")
in your database.js
-file. 您的代码几乎不需要更改,只需在npm i -S mysql2
或yarn add mysql2
,然后在database.js
-file中将行require("promise-mysql")
更改为require("mysql2/promise")
。 Possibly updating configuration in your config.js
to match additional options you can use for the connection pool. 可能会更新config.js
配置,以匹配可用于连接池的其他选项。 Otherwise mysql2
is largely API-compatible with mysql
. 否则mysql2
在很大程度上与mysql
API兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.