Sequelize 在创建时抛出“id 必须是唯一的”

问题描述 投票:0回答:2

Sequelize 库的新功能。根据我的理解,“id”是由sequelize自动创建的(这就是我在数据库中看到的)。但是,当我去“创建”一个对象时,它会抛出此错误:

    { [SequelizeUniqueConstraintError: Validation error]
  name: 'SequelizeUniqueConstraintError',
  message: 'Validation error',
  errors: 
   [ { message: 'id must be unique',
       type: 'unique violation',
       path: 'id',
       value: '1' } ],
  fields: { id: '1' } }

有问题的代码:

  db.Account.create({
    email: req.body.email,
    password: req.body.password,
    allowEmail: req.body.allowEmail,
    provider: 'local',
    role: 'user'
  })

通知 ID 未在任何地方指定,也未在我的模型定义中指定。如果我在 postgres admin 中运行它,它生成的查询也运行良好:

INSERT INTO "Accounts" ("id","email","role","verifyCode","provider","cheaterScore","isBanned","allowEmail","updatedAt","createdAt") VALUES (DEFAULT,'[email protected]','user','','local',0,false,false,'2016-01-27 04:31:54.350 +00:00','2016-01-27 04:31:54.350 +00:00') RETURNING *;

对我在这里可能缺少的东西有什么想法吗?

编辑:

postgres版本:9.5 堆栈跟踪从这里开始: /node_modules/sequelize/lib/dialects/postgres/query.js:326

node.js sequelize.js
2个回答
12
投票

Postgres 有一个习惯,即在批量插入后不重置序列中的下一个数字(自动增量字段)。因此,如果您要在 init 例程中或从 SQL 转储文件中预填充数据,这可能就是您的问题。

查看这篇文章https://dba.stackexchange.com/questions/65662/postgres-how-to-insert-row-with-autoincrement-id


0
投票

TLDR:使用:

await sequelize.query(`ALTER SEQUENCE "SharedLogs_id_seq" RESTART WITH ${maxId};`);

这是我的打字稿完整迁移代码,它可以进行批量插入并相应地更改 postgres 序列:

import {Migration, MigrationParams} from '../../types/db.migrations';
import {SharedLogRecord/* , SharedStateRecord*/} from '../../types/db';
import fs from 'fs';

type SharedLogRecordFromSqlite = SharedLogRecord & {
  updatedAt: string;
  deletedAt: string;
};

export const up: Migration = async ({context: queryInterface}: MigrationParams) => {
  const data: SharedLogRecordFromSqlite[] = JSON.parse(fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'));

  let maxId: number = 0;
  data.forEach((record: SharedLogRecordFromSqlite) => {
    delete record.updatedAt;
    delete record.deletedAt;

    if (record.id > maxId) maxId = record.id;
  });
  maxId++;

  await queryInterface.bulkInsert('SharedLogs', data);

  await queryInterface.sequelize.query(`ALTER SEQUENCE "SharedLogs_id_seq" RESTART WITH ${maxId};`); // <--- key line
};

export const down: Migration = async () => {};

module.exports = {up, down};

请参阅:https://stackoverflow.com/a/8750984/10099510

© www.soinside.com 2019 - 2024. All rights reserved.