【发布时间】:2022-01-13 21:44:20
【问题描述】:
我正在使用 mac 并安装 postgresql 数据库。
brew services start postgresql
psql (14.1, server 12.9)
我创建了角色和数据库。
psql postgres
CREATE ROLE helxsz WITH LOGIN PASSWORD 'password';
ALTER ROLE helxsz CREATEDB;
CREATE DATABASE sales;
使用pgAdmin4连接数据库成功如下图
那我想用knex和nodejs连接数据库。
const config = {
development: {
client: 'pg',
connection: {
host : '127.0.0.1',//process.env.POSTGRES_HOST,
port : 5432 ,//Number(process.env.POSTGRES_PORT),
user : 'helxsz',//process.env.POSTGRES_USER,
password : 'password',//process.env.POSTGRES_PASSWORD,
database : 'sales'
},
pool: {
min: 1,
max: 10,
idleTimeoutMillis: 10000
},
acquireConnectionTimeout: 1000
}
};
// Try to connect to postgres and export it
const knex = require('knex')(config['development']);
console.log('[::Stats::] Connected to Postgres via Knex!',config['development']);
init();
async function init(){
console.log('[:] init !');
await createTable() ;
}
async function createTable () {
try {
if (!await knex.schema.hasTable('stats')) {
await knex.schema.createTable('stats', (table) => {
table.increments('id');
table.string('species').notNullable();
table.integer('age').notNullable();
});
}
console.log('[::Stats::] Created Postgres table!');
} catch (error) {
throw new Error('Unable to create Postgres table. Ensure a valid connection');
}
}
运行代码给出错误:错误:无法创建 Postgres 表。确保有效连接。
在knex上没有看到配置的问题,和连接pgAdmin4的配置是一样的。
为什么 knex 无法建立正确的连接。
【问题讨论】:
-
在我看来,这是因为您的角色没有创建表的权限。但为确保发生这种情况,请添加
error变量的结果以找出该块出错的原因。
标签: node.js postgresql knex.js