简体   繁体   English

knex 无法在正确的数据库配置中建立 postgresql 连接

[英]knex can't build a postgresql connection in the right db configuration

I am working on mac and install postgresql database.我正在使用 mac 并安装 postgresql 数据库。

brew services start postgresql
psql (14.1, server 12.9)

I created the role and database.我创建了角色和数据库。

psql postgres
CREATE ROLE helxsz WITH LOGIN PASSWORD 'password';
ALTER ROLE helxsz CREATEDB;
CREATE DATABASE sales;

using pgAdmin4 to connect the database successfully as shown below使用pgAdmin4连接数据库成功如下图

在此处输入图像描述

Then I want to use knex and nodejs to connect the database.然后我想用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');
      }
    }

Running the code gives the error: Error: Unable to create Postgres table.运行代码会出现错误:错误:无法创建 Postgres 表。 Ensure a valid connection.确保有效连接。

I don't see the problem of configuration on the knex, it is the same with the config on connecting to pgAdmin4.我在knex上没有看到配置的问题,与连接pgAdmin4的配置相同。

why knex can't build a proper connection.为什么 knex 无法建立正确的连接。

pg to 8.7.1, also node to 16.3.1 and knex to 0.95.11, now it worked pg 到 8.7.1,节点到 16.3.1 和 knex 到 0.95.11,现在它工作了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM