12

I'm trying to connect to a remote database using node-postgres.

I can connect using the psql client, but I get the error Connection terminated unexpectedly while trying to run this (with same connection string as in psql client):

const { Pool, Client } = require('pg')
const connectionString = '...'

const pool = new Pool({
  connectionString: connectionString,
})

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

const client = new Client({
  connectionString: connectionString,
})
client.connect()

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  client.end()
})

I've also been trying to connect with Sequelize ORM, but got the same error.

@EDIT

Using native mode fixed problem for client query using pg, and sequelize

const { Pool, Client } = require('pg').native

1

10 Answers 10

7

I started having the same problem, but only with long time queries, i found a possible solution by setting idleTimeoutMillis in the Pool constructor, for example to 20000 (the default value is 10000)

See https://node-postgres.com/api/pool#new-pool-config-object-

4

Working with processes that could take hours, I found the solution using Pool but setting idleTimeoutMillis and connectionTimeoutMillis both with 0. Example:

const { Pool } = require('pg')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'my_database',
  password: 'XXXX',
  port: 5423,
  idleTimeoutMillis: 0,
  connectionTimeoutMillis: 0,
});
4

All the above solution didnt worked for me. I search over the internet but didn't find any suitable solution. In the end, I found out I was entering the wrong port number in the pg client.

This is where I found my actual port number: Server > Database > Properties proper port number location

And updated it in my code. And problem was solved

1

using pg:

import pg from 'pg';  

const conStringPri = `postgres://${username}:${password}@${host}/postgres`;
  const Client = pg.Client;
  const client = new Client({connectionString: conStringPri});
  client.connect();

  client.query(`CREATE DATABASE ${dataBaseName}`)
    .then(() => client.end());

Sequelize:

const sequelize = new Sequelize(dbName, username, password, {
  host: host || 'localhost',
  dialect: type || 'postgres',
  operatorsAliases,
  pool: {
    max: 5,
    min: 0,
    idle: 300000,
    acquire: 300000
  },
  port: port || 5432,
  logging: log => console.log('logging:', log)
});

const models = {};
// read all models from same folder
glob.sync(path.join(__dirname, '**/*.js'))
  .forEach(file => {
    const model = sequelize.import(file);
    models[model.name] = model;
  });

Object.keys(models).forEach(model => {
  if (models[model].associate) {
    models[model].associate(models);
  }
});

models.user.create(userObject);
models.user.findAll({where: {name: 'john'}});
1

I did a lot of research to solve this problem. These pg configurations solved my problem

  acquireConnectionTimeout: 5000,
  pool: {
    min: 0,
    max: 10,
    createTimeoutMillis: 8000,
    acquireTimeoutMillis: 8000,
    idleTimeoutMillis: 8000,
    reapIntervalMillis: 1000,
    createRetryIntervalMillis: 100,
  },
2
  • what max : 10 is going to do ?
    – SAURABH
    Jan 9 at 7:16
  • Determines the maximum number of threads that can occur in the pool. If the number of jobs increases, a new thread will be created up to the maximum specified number. Jan 10 at 6:24
0

I got this error the first time that worked with Postgres. I didn't know that the default port for Postgres is 5432. Changing the port to 5432 in my DB node config resolved the issue.

const db = knex({
    client: 'postgres',
        connection: {
            host: 'localhost',
            user: 'postgres',
            password: 'admin4321',
            database: 'postgres',
            port: 5432,
        }
    })
0

This may be related to the minimum pool size set to a number greater than 0.

The pool keeps the minimum amount of connections there even if they are terminated. Assigning 0 to the minimum size and also a defining good idle timeout value, maybe 1-5 minutes, can prevent this from happening.

This was discussed in an issue from knex.

0

I have tried this, problem is asynchronous property of JavaScript. Connection is being ended before execution of query.

Code below is working try this.

const express = require("express")
const app = express()
const logger = require("morgan");
const {Client} = require("pg")
const Pool = require("pg").Pool
//pool for table queries

const pool = new Pool({
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    host: "localhost",
    port: process.env.DBPORT,
    database: 'resume'
})

//middlewares
app.use(logger('dev'));
app.use(express.json());

//client1 for creating database
const client1 = new Client({
    host: 'localhost',
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    port: process.env.DBPORT
})

//client2 for table
const client2 = new Client({
    host: 'localhost',
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    port: process.env.DBPORT,
    database: 'resume'
})
//DB
const createDB = async () => {
    try {
        await client1.connect();
        console.log("creating db")
        await client1.query("create database resume;")
        console.log("created db")
    }
    catch (err) {
        console.log("Already created")
    }
    finally {
        await client1.end();
    }
}
//TABLE
const createTable = async () => {
    try {
        await client2.connect()
        console.log("creating Table")

        await client2.query(`create table resume(
            data jsonb
        )`)
        console.log("created Table")
    }
    catch (err) {
        console.log("Table already created")
    }
    finally {
        await client2.end()
    }
}
//port
app.listen(PORT, async () => {
    console.log(`Running at port ${PORT}...`)
    await createDB()
    await createTable()
})
0

I got the API port and PostgreSQL port mixed up.When I corrected the port number in my code, it functioned properly.

1
  • That might have worked in your case, but there's no indication that it's the case for the OP. If it were, this would have just been a typo and would have been likely closed
    – camille
    May 31 at 1:59
-1

Try this:

var pg = require('pg');
const client = new pg.Client(
{
    user: 'username',
    host: 'host',
    database: 'myDb',
    password: 'secretPswd',
    port: portnum,
});
client.connect(function (err){
    if(err)
        console.log(err);
    else
        console.log("Connected!");
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.