【问题标题】:inserting id to postgresql query using node.js使用 node.js 将 id 插入到 postgresql 查询中
【发布时间】:2019-01-10 04:22:57
【问题描述】:

var Integer = require('integer');

client.query('INSERT INTO users (id, first_name, last_name, email, password, phone_number) VALUES ($1, $2, $3, $4, $5, $6)', [Integer(), req.body.firstName, req.body.lastName, req.body.username, pwd, req.body.phoneNumber]

这是我尝试将 id 发布到我的 postgreqsl 表的函数。 我通过 npm 为节点安装了整数,在 pg 中为我的 id 列设置整数数据类型,当我试图将它放入数据库时​​它不起作用。

我遇到了这样的错误:

{ 错误:整数的无效输入语法:"{"high":0,"low":0}"

当我将 uuivdv4 导入文件并通过 uuidv4() 更改 Integer() 时,(当然我记得更改 id 列中的数据类型)我有一个很好的插入。

const uuidv4 = require('uuid/v4');

client.query('INSERT INTO users (id, first_name, last_name, email, password, phone_number) VALUES ($1, $2, $3, $4, $5, $6)', [uuidv4(), req.body.firstName, req.body.lastName, req.body.username, pwd, req.body.phoneNumber]

【问题讨论】:

  • 请澄清您的问题以及您的预期行为。 integer 库是一个外部包,它在 JS 中环绕原生 Number,并返回一个 Object - 这就是为什么你会收到一个 invalid input syntax for integer 错误。
  • 您可以在查询中省略id。我的意思是,如果那是传统上的 PK,它有一个 auto_increment 属性状态或时间戳属性集。所以离开id,让数据库来做这件事。另外,您还可以插入 null 代替 Integer() ,这将做同样的事情
  • 我唯一想要的就是让我的用户表的 id 自动递增。id 不能为空,因为我在数据库中设置了一个非空属性。

标签: javascript node.js database postgresql


【解决方案1】:

integer 包不打算生成像uuid/v4 那样的随机整数,它会生成随机 UUID 字符串。整数用于将字符串文字转换为数字,例如'123'123

以下内容对您有用。

更新代码:

let randNumber= Math.floor(Math.random() * 10000000000);
client.query('INSERT INTO users (id, first_name, last_name, email, password, phone_number) VALUES ($1, $2, $3, $4, $5, $6)', [randNumber, req.body.firstName, req.body.lastName, req.body.username, pwd, req.body.phoneNumber]

编辑: 将用户中的 Id 列更改为 auto-increment 并使用以下查询插入。

client.query('INSERT INTO users (first_name, last_name, email, password, phone_number) VALUES ($1, $2, $3, $4, $5)', [req.body.firstName, req.body.lastName, req.body.username, pwd, req.body.phoneNumber]

修改为autoincrement后,插入时无需指定id

【讨论】:

  • 感谢您的回答,但我如何为每个插入添加简单的 id(不是随机的)?
  • 您可以将 db 列 'id' 设置为自动增量,以便它会自动生成 id。无需显式插入
  • 谢谢,我改变了我的 id 列的整数数据类型,它在 postgresql 中是 auto_incremented 并且可以工作!
猜你喜欢
  • 2013-06-23
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
相关资源
最近更新 更多