javascript - sequelize 在验证错误时递增 id

标签 javascript postgresql sequelize.js

Sequelize 正在递增 id,即使它没有将它添加到数据库中也是如此。

例如我的用户模式:

var User = sequelize.define("User", {
    email: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false,
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false,
    },
},

如果我跑

var newUser = User.create({
        email: "a",
        password: "a"
    })

我得到 id 1,但如果我再次运行它,我会收到验证错误

下一步,如果我用不同的电子邮件运行它

var newUser = User.create({
        email: "b",
        password: "a"
    })

id 是 3,即使数据库只有 2 个条目(id 1 和 3)

我不太明白为什么 id 一直在增加,即使它没有被添加到数据库中。有什么办法可以解决这个问题吗?

最佳答案

Sequelize 不提供 id 值,PostgreSQL 本身提供。据推测,Sequelize 对 id 列使用了 serial 类型,并从数据库序列和 fine manual 中获取其值。 :

Note: Because smallserial, serial and bigserial are implemented using sequences, there may be "holes" or gaps in the sequence of values which appears in the column, even if no rows are ever deleted. A value allocated from the sequence is still "used up" even if a row containing that value is never successfully inserted into the table column. This may happen, for example, if the inserting transaction rolls back. See nextval() in Section 9.16 for details.

您正在尝试执行违反唯一性约束的 INSERT,并且存在您的回滚事务。

您不应该浪费时间关心特定的 id 值,它们是唯一的数字,这才是最重要的。

关于javascript - sequelize 在验证错误时递增 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322667/

相关文章:

sequelize.js - sequelize => 为什么不能在我包含其他关联表时排除返回的属性

sequelize.js - 如何在 Sequelize where 查询中过滤日期类型

sql - 在 postgresql 中锁定表

postgresql - 将模型迁移到数据库 Prisma 时出错

python - OSError :/usr/lib/libgdal. so.20: undefined symbol :sqlite3_column_table_name

javascript - 重组 Sequelize 结果

javascript - 为什么 $.each 使数组对象未定义,但 for 循环有效

javascript - 在 javascript/jQuery 中有类似 isset of php 的东西吗?

javascript - 只要单击页面上的任何内容, Bootstrap 工具提示就会停止工作

javascript - 将 <a> 标记的 href 值链接到另一个 html 页面