【问题标题】:knex can't build a postgresql connection in the right db configurationknex 无法在正确的数据库配置中建立 postgresql 连接
【发布时间】: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


【解决方案1】:

pg 到 8.7.1 ,节点到 16.3.1 和 knex 到 0.95.11,现在它工作了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2016-03-11
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多