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
andbigserial
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. Seenextval()
in Section 9.16 for details.
您正在尝试执行违反唯一性约束的 INSERT,并且存在您的回滚事务。
您不应该浪费时间关心特定的 id
值,它们是唯一的数字,这才是最重要的。
关于javascript - sequelize 在验证错误时递增 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322667/