Javascript'号码'和postgres类型

时间:2014-08-19 16:06:37

标签: javascript node.js postgresql

我正在通过pg包使用带有node.js的postgres,我只是开始了所以我的目标是创建一个非常简单的表格,如下所示:{{1} shell命令

psql

节点文件的相关部分如下所示。我所要做的就是得到当前人数的计数(这很好),将其递增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,其中没有任何问题,名称在postgres中存储得很好,但express列仍为空白。

我有

  • 在postgres中创建字段时尝试了idnumeric两种类型,但没有区别
  • 假设问题是在postgres中定义的类型之间的不兼容性,以及javascript中更宽松的定义,我试图转换类型int,再次无济于事
  • 我认为VALUES ($1::int, $2)项目可能是一个解决方案,但据我所知,它不是(我可能错了)
  • 如果我使用[node-pg-types][1]next(或任何其他数字/字符串)替换client.query来电中的1变量,则'1'将在postgres中显示为id

1 个答案:

答案 0 :(得分:4)

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


});