sequelize-typescript HasMany association throw error

176 Views Asked by At

I am tring to give the Table User multiple associations, I made one already with @BelongsToMany, but if I try to add @HasMany the console throw this error : SequelizeDatabaseError: there is no unique constraint matching given keys for referenced table "Users"

This is my UserM.ts Model

import {
  Table,
  Column,
  Model,
  PrimaryKey,
  Default,
  DataType,
  AllowNull,
  Unique,
  BelongsToMany,
  HasMany,
} from "sequelize-typescript";
import { Role } from "../types";
import UserLists from "./Associations";
import List from "./ListM";
import Note from "./NoteM";

@Table({
  paranoid: true,
  timestamps: true,
})
export default class User extends Model {
  @PrimaryKey
  @Column
  idUser!: number;

  @AllowNull(false)
  @Column
  nickname!: string;

  @AllowNull(false)
  @Unique
  @Column
  email!: string;

  @AllowNull(false)
  @Default(false)
  @Column
  verifiedEmail!: boolean;

  @AllowNull(false)
  @Column
  password!: string;

  @Default("Client")
  @Column
  role!: Role;

  @Default("urlAvatar")
  @Column(DataType.TEXT)
  avatar!: string;

  @BelongsToMany(() => List, () => UserLists)
  lists!: List[];

  // This association here is what I added last
  @HasMany(() => Note, "authorId")
  notes!: Note[];
}

And this is my NoteM.ts where I want the association with User

import {
  BelongsTo,
  Column,
  ForeignKey,
  Model,
  PrimaryKey,
  Table,
} from "sequelize-typescript";
import User from "./UserM";

@Table
export default class Note extends Model {
  @PrimaryKey
  @Column
  idNote!: number;

  @Column
  title!: string;

  @Column
  content!: string;

  //The code below its for the association with the table User
  @ForeignKey(() => User)
  @Column
  authorId!: number;

  @BelongsTo(() => User)
  author!: User;
}

I tried:

--To add @Unique everywhere but it doesnt work.

--Compare my code to this repo https://github.com/BigsonLvrocha/relay-modern-typescript-server and I opened two routes

relay-modern-typescript-server/src/models/Post.model.ts

relay-modern-typescript-server/src/models/User.model.ts

Those routes doesnt have @Unique anywhere and has the @HasMany model association

I don’t know if it has anything to do, but I have my database in elephantDB.

Git repo: https://github.com/Koppeks/Api-ts

Dependencies versions:

"typescript": "4.9.5"
"sequelize": "6.28.0"
"sequelize-typescript": "2.1.5"
1

There are 1 best solutions below

0
Elbongo On

I manage to fix this issue by doing the following

I had to rename every file exactly the same as the exported class inside the file. For example:

export class User extends model{}

This needs to be named User.ts.

Also I had alter:true on the sequelize.sync, which tries to perform changes to match the table on your VsCode with the one in the database to match the model.