gpt4 book ai didi

node.js - Sequelize node js create record with autoincrement field 验证错误

转载 作者:行者123 更新时间:2023-11-29 14:31:34 26 4
gpt4 key购买 nike

我有 Sequelize 模型:

'use strict';

module.exports = (sequelize, DataTypes) => {
const Image = sequelize.define('Image', {
id: {
type: DataTypes.BIGINT,
autoIncrement: true,
unique: true,
primaryKey: true
},
url: {
type: DataTypes.STRING,
allowNull: false,
}
},
{
timestamps: false
});

Image.associate = (models) => {
//some association here
};

return Image;
};

我正在尝试创建这样的新记录:

const img = await Images.create({
url: '/newUrl'
}).catch(error => {
throw errors.initError(error);
});

它执行一个查询

Executing (default): INSERT INTO "Images" ("id","url") VALUES (DEFAULT,'/newUrl') RETURNING *;

我收到一个错误

{
"message": "id must be unique",
"type": "unique violation",
"path": "id",
"value": "18",
"origin": "DB",
"instance": {
"id": null,
"url": "/newUrl"
},
"validatorKey": "not_unique",
"validatorName": null,
"validatorArgs": []
}

sequelize 不应该自己处理自增字段吗?

最佳答案

当您手动在提供 id 的数据库中创建条目时,就会发生这种情况。

为了演示这一点,您可以在 postgres 中尝试这些

create table users (id serial NOT NULL PRIMARY KEY, name varchar(40));
insert into users (name) values ('abhinavd');
select * from users;
insert into users (id, name) values (2, 'abhinavd');
insert into users (name) values ('abhinavd');

最后一次插入会失败,提示 id 必须是唯一的

Duplicate key

关于node.js - Sequelize node js create record with autoincrement field 验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com