Joh*_*min 15 javascript node.js sequelize.js node-postgres
我正在尝试使用 node-postgres 连接到远程数据库。
我可以使用 psql 客户端进行连接,但在尝试运行此程序时出现错误Connection terminated unexpectedly(使用与 psql 客户端相同的连接字符串):
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()
})
Run Code Online (Sandbox Code Playgroud)
我也一直在尝试连接 Sequelize ORM,但遇到了同样的错误。
@编辑
使用本机模式修复了使用 pg 和 Sequelize 进行客户端查询的问题
const { Pool, Client } = require('pg').native
小智 8
我开始遇到同样的问题,但只有长时间查询时,我通过在Pool构造函数中设置idleTimeoutMillis找到了可能的解决方案,例如设置为 20000 (默认值为 10000)
请参阅https://node-postgres.com/api/pool#new-pool-config-object-
在处理可能需要数小时的流程时,我找到了使用Poolbut 设置idleTimeoutMillis并将connectionTimeoutMillis两者都设置为 0 的解决方案。示例:
const { Pool } = require('pg')
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'my_database',
password: 'XXXX',
port: 5423,
idleTimeoutMillis: 0,
connectionTimeoutMillis: 0,
});
Run Code Online (Sandbox Code Playgroud)
Dmy*_*sak -1
使用 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());
Run Code Online (Sandbox Code Playgroud)
续集:
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'}});
Run Code Online (Sandbox Code Playgroud)