Get Customised Columns using TypeOrm Query

Get Customised Columns using TypeOrm Query

Sometimes while making our models (table) we declare some columns which are only to be used for tracking the entry and updation of the data like the created_at and updated_at columns. We often declare its select type as false because we don't need it to be present in our data.

@CreateDateColumn({ select: false, type: 'timestamp' })
  createdAt: Date;

  @UpdateDateColumn({ select: false, type: 'timestamp' })
  updatedAt: Date;

QueryBuilder is one the most efficient way to filter out columns from a table, but writing a query using .createQueryBuilder() is sometimes a bit confusing and also not necessary. On writing a normal query using getRepository(), we get the data without having information on these columns. It might be a case that sometime you may need this column information for some time-related operations. One way to get this information is by using a query builder.

 await getCustomRepository(User)
      .createQueryBuilder('user')
      .where('user.email = :email', { email})
      .select(['user.id','user.created_at','user.updated_at'])
      .getOne(); // for multiple data use .getMany()

Using TypeOrm Find() for customised columns.

You can also use typeorm find() to get specific columns from the table. You need to use select() within find conditions and provide the required columns.

await getRepository(User).find({
           where:{email:'demo@abc.com'},
           select:['id',"createdAt","updatedAt"]
         });

This way you can get all the columns which are selected as false by default in your model and are not fetched on running the normal query.

Conclusion

Columns which are by default selected as false in the model (table) can only be retrieved when we specifically select this column using query builder or build-in methods of typeorm query.