Using 'sequelize-typescript' I want to populate the membersId with the Users connected to each UUID in the array. Also I'm not sure if the One-to-Many association I made between the two tables is correct. My understanding is that every chat has one owner which is a User and a User has many chats. But at the same time because chats have members they will also have access to the chat. So shouldn't it then be a Many-to-Many relationship? Confused as to how this works. Thank you.
The Chat Model
@Table({
freezeTableName: true,
timestamps: true
})
class Chat extends Model {
@Column({
primaryKey: true,
type: DataType.UUID,
defaultValue: DataType.UUIDV4
})
declare id: string;
@Column({
type: DataType.JSONB,
allowNull: false,
validate: {
notEmpty: true,
atleastTwoMembers(members: string[]) {
if (Array.isArray(members) && !(members.length >= 2)) {
throw new Error('Invalid Member Count!');
}
if (!Array.isArray(members)) {
throw new Error('Invalid Member Count!');
}
}
},
defaultValue: []
})
declare membersId: User[];
@ForeignKey(() => User)
@Column({
type: DataType.UUID,
allowNull: false,
validate: {
notEmpty: true
}
})
declare chatOwnerId: string;
@BelongsTo(() => User)
declare chatOwner: User;
declare chatOwner: User;
@CreatedAt
declare createdAt: Date;
@UpdatedAt
declare updatedAt: Date;
}
export default Chat;
And then I have a User Model
@Table({
freezeTableName: true,
timestamps: true
})
class User extends Model {
@Column({
primaryKey: true,
type: DataType.UUID,
defaultValue: DataType.UUIDV4
})
declare id: string;
@Column({
type: DataType.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true
}
})
declare name: string;
@Column({
type: DataType.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true,
isEmail: true
}
})
declare email: string;
@Column({
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
})
declare password: string;
@HasMany(() => Chat)
declare allChats: Chat[];
declare
@CreatedAt
declare createdAt: Date;
@UpdatedAt
declare updatedAt: Date;
}
export default User;
I am using pg as the database.