【问题标题】:Why can't I rename this object in my node application?为什么我不能在我的节点应用程序中重命名这个对象?
【发布时间】: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


【解决方案1】:

当您执行const { rows } = xxx 时,您正在使用object destructing 将xxx.rows 属性分配给本地范围内与该属性同名的新变量。

因此,当您将该属性的名称更改为其他名称时:

const { myVar } = xxx;

代码现在正在寻找属性xxx.myVar,它可能不存在,因此最终是undefined。

如果您想使用不同的名称,则必须使用不同形式的对象解构赋值(包括新名称)或根本不使用解构,只需将 .rows 属性分配给新变量。

例如,您可以这样做:

const result = await pool.query(`
            SELECT id, password
            FROM myschema.users
            WHERE username = $1
            LIMIT 1;`,[username]);

const myVar = result.rows;

或者您可以在对象解构赋值中指定一个新名称:

const {rows: myVar} = await pool.query(`
            SELECT id, password
            FROM myschema.users
            WHERE username = $1
            LIMIT 1;`,[username]);

console.log(myVar);

【讨论】:

  • 谢谢。列出备选方案非常有帮助。
【解决方案2】:

这称为Object destructuring。当你做这样的事情时

const { row } = someObject

那么变量row 等于row property of someObject。但是如果someObject 甚至没有任何row 属性,那么row 显然将是undefined。

您的情况也是如此。 await pool.query(... 返回的对象具有rows 属性,这就是为什么const { rows } 有效但它没有userdetails 属性因此undefined。

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 2017-07-11
    相关资源
    最近更新 更多