【问题标题】:Sequelize node js create record with autoincrement field validation errorSequelize node js创建带有自动增量字段验证错误的记录
【发布时间】:2021-10-17 20:13:00
【问题描述】:

我有续集模型:

'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);
});

它执行一个查询

执行(默认):INSERT INTO "Images" ("id","url") VALUES (DEFAULT,'/newUrl') 返回 *;

我收到一个错误

{
  "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句柄自增字段吗?

【问题讨论】:

标签: node.js postgresql sequelize.js


【解决方案1】:

当您在提供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 必须是唯一的

【讨论】:

  • 那么我们如何让它再次开始自动递增呢?
  • 为这个问题提供解决方案会很棒
【解决方案2】:

当您插入记录并手动提供 ID 时会发生这种情况。 next_val('test_id_seq') 仅在系统需要此列的值并且您没有提供值时才调用。您需要做的是更新这个 next_val 值。

要解决此问题,您可以在表中执行以下操作

   SELECT setval('YourTable_id_seq', (SELECT MAX(id) from "YourTable"));

序列的名称总是自动生成的,它遵循以下格式 tablename_columnname_seq。

【讨论】:

    【解决方案3】:

    为了补充 Rodolofo 的答案,Postgres 用户应将 'YourTable_id_seq' 替换为 '"YourTable_id_seq"'。表名区分大小写。

    Refer this answer

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2022-10-09
      • 2014-04-24
      • 2015-03-06
      • 2020-01-29
      相关资源
      最近更新 更多