How to exclude a column from typeorm entity and could be optional to get the column using Find method

Issue

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@Column()
password: string;
}

i dont want password here because i want to return to client:

const user = await User.find({where:{name:"test"}})

when i want to modify password i need password:

const user = await User.findOne({where:{name:"test"}})
user.password="password";
await user.save()

is there any solution with Find,FindAndCount or even FindOne methods?

How should i do?

Solution

You could add a select option in your @Column decorator inside the entity like this:

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

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

This way you will not get the password field from the model if you do find. You’ll have to explicitly do addSelect using QueryBuilder.

Reference: https://typeorm.io/#/select-query-builder/hidden-columns

Answered By – Rahul Sharma

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published