我有一个现有的带有Rails的postgresql数据库,现在我正在创建一个使用相同数据库的Node.js应用程序。我的数据库中已有用户,现在我想列出所有用户。
我成功创建了一个快速应用,然后我做了如下:
✗ npm install --save sequelize pg pg-hstore
✗ sequelize init
index.js
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const pg = require('pg');
var conString = 'postgres://localhost:5432/db_name';
var client = new pg.Client(conString);
const app = express();
client.connect(err => {
if (err) {
console.error('connection error', err.stack);
} else {
console.log('connected');
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.send(models.User.findAll);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT);
在config.json
我有:
"development": {
"username": "my_username",
"password": null,
"database": "database_name",
"host": "127.0.0.1",
"dialect": "postgres"
}
我收到此错误:UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
我可能错过了一大步,但我不知道它是什么,我以前从未这样做过。
答案 0 :(得分:1)
示例查询
const query = {
text: 'CREATE TABLE IF NOT EXISTS coverages ('+
'vaccine VARCHAR(64),' +
'country VARCHAR(255),' +
'region VARCHAR(255),' +
'year VARCHAR(4),' +
'value VARCHAR(12),' +
'PRIMARY KEY(vaccine, country, region, year, value))'
};
client.query(query)
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log('\nError executing query', err.stack);
});
答案 1 :(得分:1)
以下是使用async / await的一些示例查询(我相信它需要Node 8+,因此请确保您的版本支持此功能):
var express = require('express');
var pg = require('pg');
var router = express.Router();
let conString = 'postgres://localhost:5432/db_name';
var postgrespool = new pg.Pool({
connectionString: conString
});
router.get('/checkdbconnection', function(req, res, next) {
(async () => {
// Here is the query!
// alter it to query a table in your db
// this example just confirms a connection
var { rows } = await postgrespool.query(`
SELECT
'Hello from Postgres' AS pg_val;`);
if (rows.length) {
return res.send(rows);
} else {
res.status(404);
return res.send('No response from database.');
}
})().catch(e =>
setImmediate(() => {
res.status(500);
console.log(e);
return res.send('Error: ' + e.message);
})
);
});
router.get('/checkdbconnection/:name', function(req, res, next) {
let param_name = req.params.name;
(async () => {
// this example demonstrates how to pass parameters to your query with $1, $2, etc.
// usually, the cast of "::text" won't be necessary after the "$1"
var { rows } = await postgrespool.query(`
SELECT
'Hello from Postgres' AS pg_val,
$1::text AS parameter;`, [param_name]);
if (rows.length) {
return res.send(rows);
} else {
res.status(404);
return res.send('No response from database.');
}
})().catch(e =>
setImmediate(() => {
res.status(500);
console.log(e);
return res.send('Error: ' + e.message);
})
);
});
module.exports = router;
如果您访问http://localhost:5000/checkdbconnection,则会收到此回复:
[
{
"pg_val": "Hello from Postgres"
}
]
如果你访问,比如http://localhost:5000/checkdbconnection/Al-josh,你就会得到这个:
[
{
"pg_val": "Hello from Postgres",
"parameter": "Al-josh"
}
]
希望我在代码中的注释已经清楚地说明查询是如何工作的,因此您可以根据自己的需要对其进行更改。如果没有,请提供有关您的表格的更多详细信息,我可以修改此答案。
另请注意,我在这里使用 pg.Pool 连接到Postgres。这完全是您的问题的次要问题,但the documentation值得一读。