【问题标题】:Javascript 'number' and postgres typesJavascript 'number' 和 postgres 类型
【发布时间】:2014-08-20 00:25:59
【问题描述】:

我通过pg 包将postgres 与node.js 一起使用,我才刚刚开始,所以我的目标是一个非常简单的表格,如下所示,由psql shell 创建命令

CREATE TABLE people(id int, name text);

Column   |  Type   | Modifiers
------------+---------+-----------
    id   | int     |
    name | text    |

节点文件的相关部分如下所示。我要做的就是计算当前人数(这很好),将其增加1 并将这个新值用作我添加到表中的下一个人的id

pg.connect(conString, function(err, client) {
  var count;
  var next;

  client.query('SELECT COUNT(*) FROM people', function(err, result) {
    count = result.rows[0].count;
    next = Number(count)+1;
  });

  client.query('INSERT INTO people (id, name) VALUES ($1, $2)', [next, req.body.personName],function(err, result) {
  });
});

req.body.personName 正在express 应用程序的其他位置设置,这部分没有问题,名称在 postgres 中存储良好,但id 列保持空白。

我有

  • 在 postgres 中创建字段时尝试了 numericint 类型,但没有任何区别
  • 假设问题是在 postgres 中定义的类型之间不兼容,而在 javascript 中定义较松散,我尝试将类型转换为 VALUES ($1::int, $2) ,再次无济于事
  • 我认为[node-pg-types][1] 项目可能是一个解决方案,但据我了解,它不是(我很可能错了)
  • 如果我将client.query 调用中的next 变量替换为1'1'(或任何其他数字/字符串),那么1 将在postgres 中显示为ID

【问题讨论】:

  • 好的,console.log(result.rows[0].count) 给出了0(表是空的,所以正确),但它的类型是string。不确定alias 建议是什么意思?你能扩展一下吗?

标签: javascript node.js postgresql


【解决方案1】:

看起来您正在同时做两件事(异步)。查询完成后尝试 INSERT(在回调中):

pg.connect(conString, function(err, client) {
  var count;
  var next;

  client.query('SELECT COUNT(*) FROM people', function(err, result) {
    count = result.rows[0].count;
    next = Number(count)+1;
    client.query('INSERT INTO people (id, name) VALUES ($1, $2)', [next,              
       req.body.personName],function(err, result) {
    });
  });


});

【讨论】:

  • 工作就像一个魅力,谢谢!我觉得自己像个白痴,我错过了!
猜你喜欢
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 2020-08-07
  • 2019-09-29
  • 2023-03-19
  • 2023-02-11
  • 2017-01-05
  • 2022-01-16
相关资源
最近更新 更多