【发布时间】:2019-07-22 15:33:39
【问题描述】:
我正在使用 postgresql 数据库创建 nodejs 后端应用程序。我想要的是,一旦我在我的 db.js 文件中创建了与数据库的连接,我就可以在其他文件中重用它来执行查询。
这是我的 db.js 文件
const pool = new Pool({
user: 'us',
host: 'localhost',
database: 'db',
password: 'pass',
port: 5432,
})
pool.on('connect', () => {
console.log('connected to the Database');
});
module.exports = () => { return pool; }
这就是我尝试在 index.js 文件中使用它的方式
const db = require('./db.js')
app.get('/', (request, response) => {
db().query('SELECT * FROM country'), (error, results) => {
if (error) {
response.send(error)
}
console.log(results)
response.status(201).send(results)
}
})
没有任何错误,当我转到这个特定页面时,它一直在加载。控制台中也没有任何内容。
但是,如果我在我的 db.js 文件中编写一个函数并执行pool.query(...) 之类的操作,将其导出,然后在我的 index.js 中编写app.get('/', exportedFunction),一切正常。
有什么方法可以不在一个 (db.js) 文件中编写所有(例如 50 个)查询,因为我想稍微组织一下我的项目?
【问题讨论】:
-
能分享一下你在db.js文件中写的函数吗?
标签: javascript node.js postgresql express pool