Search code examples
typescripttypeorm

Exclude selected fields in typeorm responses, exclude the password field


I have this TypeORM entity:

export class Users extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: bigint

  @Column({ type: 'varchar', length: 32 })
  username: string

  @Column({ type: 'varchar', length: 32 })
  password: string
}

when I use the method:

const data = await Users.find({})

I get all the users with their passwords. I want to exclude the password field from the response.

According to the documentation, I found that you can specify the select option as follows:

const data = await Users.find({ select: { username: true, password: false } })

This works, However, this is just an example.

In my real case, the user table has over 26 columns.

And I don't want to list every column in the select options as

const data = await Users.find({ select: { 
   username: true, 
   firstName: true,
   lastName: true,
   // ... other 99,999,99+ columns
   // then eventually:
   password: false 
} })

Is there a simpler solution where I can simply do something like a pre-fetch middleware, or define that it should be excluded in the schema?

In mongoose, I used to write password: { select: false } inside the schema itself.

Are there any methods we can do for TypeORM?


Solution

  • New answer:

    Well, it turned out, this feature is already supported in typeorm, all you have to do is to use the select option, you can find this option inside the @Column decorator, as follows:

    export class Users extends BaseEntity {
      @Column({ select: false })
      password: string
     
      // ...etc
    }
    

    Old answer:

    I found a cool way for doing it.

    $ npm i class-transformer
    

    Then, in your entity:

    import { Exclude } from 'class-transformer'
    
    export class Users extends BaseEntity {
      @PrimaryGeneratedColumn()
      id: bigint
    
      @Column({ type: 'varchar', length: 32 })
      username: string
    
      @Column({ type: 'varchar', length: 32 })
      @Exclude()
      password: string
    }
    

    After that, in your code, whenever you fetch the data, before sending it to the client, convert the returned TypeORM class instances to POJO (Plan Old JavaScript Objects):

    import { instanceToPlain } from 'class-transformer'
    const data = await Users.find()
    const dataPOJO = data.map((user) => instanceToPlain(user))
    // now dataPOJO includes everything except the 'password' field.