如何使用 Typescript Sequelize 模型创建数据而不传入 id

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

我正在将 Sequelize 与 Typescript 结合使用,并寻找一种运行

Course.create()
的方法,但无法避免需要指定
id
字段来运行
.create()
方法。这是课程模型:

import { DataTypes, Model, Optional } from 'sequelize';
import db from './index';


interface CourseAttributes {
    id: string;
    name: string;
    city: string;
    state: string;
    country: string;
};

/*
  We have to declare the CourseCreationAttributes to
  tell Sequelize and TypeScript that the property id,
  in this case, is optional to be passed at creation time
*/
interface CourseCreationAttributes
    extends Optional<CourseAttributes, 'id'> { }

interface CourseInstance
    extends Model<CourseAttributes, CourseCreationAttributes>,
    CourseAttributes {
    createdAt?: Date;
    updatedAt?: Date;
}


const Course = db.sequelize.define<CourseInstance>(
    'Course',
    {
        id: {
            type: DataTypes.UUID,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
            unique: true,
        },
        name: {
            allowNull: true,
            type: DataTypes.TEXT,
        },
        city: {
            allowNull: false,
            type: DataTypes.TEXT,
        },
        state: {
            allowNull: true,
            type: DataTypes.TEXT,
        },
        country: {
            allowNull: true,
            type: DataTypes.TEXT,
        },
    }
);



export default Course;

注意我想传递此数据而不id。我不想在发出 POST 请求时必须包含 id。但无论我做什么,我似乎总是会遇到错误

Error: Field 'id' doesn't have a default value

{
    "name": "Pebble Beach",
    "city": "San Diego",
    "state": "CA",
    "country": "US"
}

我该如何解决这个问题?

node.js typescript express sequelize.js
1个回答
0
投票

尝试

id: {
  type: DataTypes.STRING,
  allowNull: false,
  autoIncrement: true,
  primaryKey: true,
  unique: true,
  defaultValue: Sequelize.UUIDV4,
},
© www.soinside.com 2019 - 2024. All rights reserved.