【发布时间】:2017-12-04 13:37:16
【问题描述】:
我有一个 node.js/express 应用程序使用 node-postgres 模块与 Postgres 数据库通信。它与 async/await 一起工作,但如果我将返回的对象重命名为 { rows } 以外的任何内容,它会返回未定义。这是我的代码;注意async下方和const { rows } = ...上方的评论:
var express = require('express');
var router = express.Router();
const { Pool } = require('pg');
const pool = new Pool({
connectionString: 'postgresql://postgres@localhost/mydb'
});
router.post('/login', function(req, res, next) {
var username = req.body.username;
var password = req.body.password;
(async () => {
// if I rename this from "rows" to, say, "userdetails", it comes back undefined
const { rows } = await pool.query(`
SELECT id, password
FROM myschema.users
WHERE username = $1
LIMIT 1;`,[username]);
if (rows.length) {
// check password, etc, etc.
return res.status(200).send();
} else {
return res.status(401).send();
}
})().catch(e => setImmediate(() => {
res.status(500);
}
));
});
module.exports = router;
我确定我在这里遗漏了一些非常基本的东西,但是为什么我不能重命名呢? pg 模块是否以某种方式规定返回的 var/const 必须命名为 { rows }?如果是这样,我怎么会发现呢?我在await 处设置了一个断点并单步执行代码,但我仍然不清楚。
【问题讨论】:
-
以防万一,您是否要将 rows 变量的所有实例重命名为新变量名?
标签: node.js postgresql express