Search code examples
node.jsnestjstypeorm

How to manage tables for users in my database?


Let's say i have a Teacher entity and a Student one. Both of them have email and password, but teacher have additional columns, as well as student. So, it will be different tables? But in this case,i will have do create authentification module, controller, jwt strategies and all the stuff for each of them. How to keep them in the same table, but extend depending on the role?

p.s. To clarify:

This is my PassportStrategy. And i need to use teacherService here. And same for Student. A lot of redundant code. And this is not the only case.

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'email'
    });
  }
  async validate(email: string, password: string): Promise<Teacher | Student> {
    return this.authService.getAuthenticatedUser(email, password);
  }
}

Solution

  • Put the specific data in a JSON column. That will keep you having one table for all teachers and students.

    class User {
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        email: string;
    
        @Column()
        password: string;
    
        @Column({ type: 'json' })
        data: any;     //  <---------- The specific data goes into here.
    }
    

    Update

    To apply join, they should be individual entities:

    class User {
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        email: string;
    
        @Column()
        password: string;
    
        @Column()
        role: 'teacher' | 'student';
    }
    
    class Student {
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        userId: string;
        
        ...
    }
    
    class Teacher {
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        userId: string;
        
        ...
    }