我正在尝试在 node/express 应用程序中使用现有的 sqlite3 数据库设置 knex。我已经有了可以使用 SQLLiteStudio 查看的数据库,但是我无法使用 knex 连接到它。
我的 server.js 文件实现了一个主路由和一个 api 端点,如下所示:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '..', 'public');
const port = process.env.PORT || 3000;
const helpers = require('./helpers');
app.use(express.static(publicPath));
app.get('/', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.get('/api/:word',(req,res) => {
console.log(req.params.word)
helpers.fetchWord(req.params.word).then((result) => {
console.log(result)
res.status(200).json(result);
}).catch((error)=>{
console.log(error)
res.status(400).send('Could not fetch the word')
})
})
app.listen(port, () => {
console.log('Server is up!');
});
我有一个 database.js 文件,它导出我的 knex 配置和一个 helpers.js 文件,用于编写实现实际查询的函数。
Database.js 看起来像这样:
module.exports = {database: {
client: 'sqlite3',
connection: {
filename: "./openrussian.db"
},
useNullAsDefault: true
}}
Helpers.js 看起来像这样:
const knex = require('knex');
const config = require('./database');
const db = knex(config.database);
module.exports = {
fetchWord
}
async function fetchWord (word) {
return await db.select().from('nouns')
}
目前,我只是尝试进行一般选择以返回表中的所有行(以测试工作),但是在向“localhost:3000/api/word”发出获取请求时出现以下错误
[Error: select * from `nouns` - SQLITE_ERROR: no such table: nouns] {
errno: 1,
code: 'SQLITE_ERROR'
}
我知道这个表肯定存在于我现有的 .db 文件架构中,因为我能够使用 SQLLiteStudio 进行成功的查询。我怀疑 knex 实际上是在创建一个新数据库,而不是使用我现有的数据库,这就是它报告找不到表名的原因(在这种情况下,我没有创建任何模式)。
如何将现有数据库与 knex 一起使用?