Javascript & # 39;数字# 39;和postgres类型

Javascript 'number' and postgres types

本文关键字:postgres 类型 数字 Javascript      更新时间:2023-09-26

我通过pg包使用node.js的postgres,我只是开始,所以我的目标是一个非常简单的表格,如下所示,在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]项目可能是一个解决方案,但从我对它的理解,它不是(我很可能是错的)
  • 如果我用1'1'(或任何其他数字/字符串)替换client.query调用中的next变量,则1将显示为postgres
  • 中的id

看起来你同时在做两件事(异步的)。在查询完成后(在回调中)尝试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) {
    });
  });

});