TypeORM - never return the password from the database when fetching a user

I created a REST API using NestJs with TypeORM. Basically this is my user entity

export class User extends BaseEntity {
  public id: number;

  @Column({ unique: true })
  public username: string;

  public passwordHash: string;

When fetching users from the database the sensitive password information get returned too. But I only need the password field for the sign in process. So when calling the service for signing in I compare the password hash from the database user with the provided password from the client. I would never want to return the password information back to the client.

As you can image fetching users from the database happens quite often, you would have to delete the password information from the user object quite often.

Let's assume you have a group entity and have a relation between them. When fetching users related to a group you would also have to take care for the sensitive data in the groups domain.

And maybe some users are deeply nested within an object returned by a big SQL query statement. Is there a way I can "hide" some fields? When calling this.usersRepository.find() I would get a list of users and each user would have an id and a username field but not a passwordHash field. This would make things easier because I only need to fetch the hash field within my signIn flow.



Just add the select: false option to the column definition. With it, the column won't be selected unless explicitly added via addSelect, see the docs.

export class User {

    @Column({select: false})
    password: string;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.