Search code examples
node.jsdatabasetypescriptnestjstypeorm

NestJS Rest API show only some columns from database using TypeORM


I would like to show only some of the columns in the Entity using NestJS and TypeORM. These are my columns in the Entity:

@Entity({ name: "products" })
export class Product extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  quality: number;

  @Column()
  color: string;

  @Column()
  desc: string;

My repository.ts:

@EntityRepository(Product)
export class ProductRepository extends Repository<Product> {}

For example is someone wants to open products/specific it should show only the name and desc.

This is my function in services.ts now:

async get(productid: number): Promise<Product> {
    var product: Product= await this.productRepositroy.findOne(productid);
    return product;
  }

How should I modify it to return only the chosen Columns? I have read about QueryBuilders, but I have no idea how i should implement them.


Solution

  • Your repository has inherited from the method createQueryBuilder by extending Repository. Thus, you can use it with select in order to only get the expected columns:

    const product = await this.productRepository
      .createQueryBuilder('p')
      .where('p.productId = :productId', { productId })
      .select(['p.name', 'p.desc']);
      .getOne();
    

    Additionally, Nest is able to modify your outgoing objects by using a Serializer: serialization doc. But this is always a good idea to only select the required columns.

    NB: I'd also advise not mixing your business logic (here, handling "products") with your database too much (you'd better split the responsibility of Getting a product and Fetching data from the database, for testability/maintainability reasons).