【问题标题】:Express JS returns null for a query result and values are shown when queried with pgAdminExpress JS 为查询结果返回 null,并在使用 pgAdmin 查询时显示值
【发布时间】:2019-01-06 15:56:47
【问题描述】:

我有以下代码用于查询国家名称列表:

router.get('/', function(req, res) {
  console.log("/");
  const query =
    `SELECT DISTINCT name
         FROM countries`;

  db.map(query, [], a => a.json)
    .then(data => {
      res.send({
        data: data,
        status: 200
      });
    })
    .catch(error => {
      console.log(error);
      res.status(500).send('Error occured');
    });
});

作为回应,我得到如下回应:

{
  "data": [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    ........
  ],
  "status": 200
}

但是当我使用 pgAdmin 运行相同的查询时,我得到的是国家名称而不是“null”。有人可以帮我解决这个问题吗?我是初学者,不知道这里出了什么问题。

提前致谢。

【问题讨论】:

  • 执行SELECT DISTINCT name FROM countries WHERE name is NOT NULL时会发生什么?
  • 在 pgAdmin 中查询时,我得到 211 个名称,上面的代码给出了 211 个空值。与上述查询@DavidR 的结果相同
  • 你使用的是哪个 npm 模块?
  • @RahulSharma pg-promise。其他查询返回正确的结果。

标签: node.js postgresql express pg-promise


【解决方案1】:

您的查询正在选择字段name,但您正在使用名为json 的属性映射结果。您应该执行以下操作:

db.map(query, [], a => a.name)

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2021-05-29
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多