Home > Mobile >  MYSQL with sequelize and typscript can't create id automatically
MYSQL with sequelize and typscript can't create id automatically

Time:01-04

I am using typescript for the first time and I am following a tutorial. The tutorials I have seen normally use a package to generate id for the table. My question is: is there no way to allow sequelize to create the table id and auto increment? This is how I created my model based on the tutorial:

import { DataTypes, Model, } from "sequelize";
 import db from "../config/database.congfi";


 interface TodoAttributes{
  id: number,
  title: string,
  completed: boolean
}
 
 export class TodoInstance extends Model<TodoAttributes>{

  }


   TodoInstance.init(
    {
    id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
    },
    title: {
    type: DataTypes.STRING,
    allowNull: false
    },
    completed:{
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false
  }
 }, {
sequelize:db,
tableName: 'todo'
}
)

When I want to create a data inside a table, I would be asked to provide id. If I provide this manually, that makes no sense because I want the id to increment. Though I can use a third party package or use the inbuilt node crypto module.

CodePudding user response:

It's a rule of thumb to generate the primary key by DB itself. In order to achieve that you just need to indicate autoIncrement: true for the primary key field in the model definition:

TodoInstance.init(
    {
    id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
    autoIncrement: true,
    },
    title: {
    type: DataTypes.STRING,
    allowNull: false
    },
    completed:{
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false
  }

And of course if you created the table linked to this model by using sync you should recreate it again so Sequelize can indicate for the id column that it should be autoincremented.

CodePudding user response:

Maybe you want to consult the official Typescript documentation:

https://sequelize.org/docs/v6/other-topics/typescript/

There are currently two ways, (one of them is discouraged) to handle Typescript Models.

Both ways however show, how to make the "id" optional, so it will work with new entities aswell.

  • Related