How to use many-to-many association with sequelize-typescript?

Viewed 317

I'm using sequlize-typescript to create 2 models - User and Group. User can be related to many groups and each group contains many users. I have created a junction table model UserGroup and associated it to the models with @BelongsToMany. However, I'm not able to create a new group with association to existing users. The group is created but there are no users linked to it.

This is how I'm creating a group -

groupsRouter.post('/', async (req: any, res) => {
    const userId = req.user.userId;
    const groupId = uuidv4();
    try {
        const createdGroup = await Group.create({ ...req.body, groupId, creatorId: userId }); // req.body has name and users properties, users is an array of user objects.
    } catch (err) {
        // tslint:disable-next-line:no-console
        console.error(err);
    }
    res.status(200).send();
});

These are the models:

Group.ts

import { Column, Model, HasMany, ForeignKey, PrimaryKey, Table, BelongsToMany, IsUUID, AutoIncrement } from 'sequelize-typescript'
import GroupUser from './GroupUser';
import User from './User';

@Table
class Group extends Model {
    @IsUUID(4)
    @PrimaryKey
    @Column
    groupId: string;

    @ForeignKey(() => User)
    @Column
    creatorId: string;

    @BelongsToMany(() => User, () => GroupUser)
    users: User[];

    @Column
    name: string;
};

export default Group;

User.ts

import { Column, Model, PrimaryKey, Table, BelongsToMany } from 'sequelize-typescript'
import Group from './Group';
import GroupUser from './GroupUser';

@Table
class User extends Model {
    @PrimaryKey
    @Column
    userId: string;

    @Column
    firstName: string;

    @Column
    lastName: string;

    @Column
    email: string;

    @Column
    profilePic: string;

    @Column
    provider: string;

    @BelongsToMany(() => Group, () => GroupUser)
    groups: Group[];
};

export default User;

GroupUser.ts

import { Column, Model, ForeignKey, Table } from 'sequelize-typescript'
import Group from './Group';
import User from './User';

@Table
class GroupUser extends Model {
    @ForeignKey(() => Group)
    @Column
    groupId: string;

    @ForeignKey(() => User)
    @Column
    userId: string;
};

export default GroupUser;
0 Answers
Related