[FIXED] How to select fields from joined table using TypeORM repository?


I have 2 models with one-to-many connection – Post and User:

export class Post {
  @ManyToOne(() => User, (user) => user.posts) user: User;

export class User {
  @OneToMany(() => Post, (post) => post.user) posts: Post[];

To get data from database I use repositories, and my question is – how can I get only userId field from this query.

  @InjectRepository(Post) private postRepository: Repository<Post>
) {}

findAll(): Promise<Post[]> {
  return this.postRepository.find({
    relations: ['user']

Now response looks like this:

    "id": 1,
    "title": "Nam fringilla volutpat venenatis. Nulla et sem.",
    "content": "Aliquam tr...",
    "preview": "p1",
    "createdAt": "2022-08-28T11:52:44.833Z",
    "updatedAt": "2022-08-28T11:52:44.833Z",
    "user": {
      "id": 1,
      "firstName": "Timber",
      "lastName": "Saw",
      "createdAt": "2022-08-28T11:52:44.827Z",
      "updatedAt": "2022-08-28T11:52:44.827Z"

Cause now I just get the whole entity, but I want only id of user. I know, I can use createQueryBuilder, but is it possible to do using repositories?


According to the documentation, this one might help you:

    relations: {
      user: true
    select: {
      user: {
        id: true

For reference: https://orkhan.gitbook.io/typeorm/docs/find-options

Answered By – Dimi Vi

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published