findAncestorsTree doesn't return parents in TypeORM 3

92 Views Asked by At

I'm using TypeORM materialized tree. There's an entity called organization, every organization has a parent and could have several children.

@Entity('organizations')
@Tree('materialized-path')
export class Organization {
  @Column()
  name: string;

  @TreeChildren()
  children?: Organization[];

  @TreeParent()
  parent?: Organization;
}

I call findAncestorsTree to fetch parents of a child in tree. Based on TypeORM document it should return all direct child's parent organizations (with "parent of parents") but it only return the child item without any parent.

const organization = await this.organizationRepository.findOne({
   where: { id },
});
return this.dataSource.manager.getTreeRepository(Organization).findAncestorsTree(organization);

The response that I get:

{
    "id": "1",
    "name": "A3-121"
}

What I expected to get:

{
    "id": "1",
    "name": "A3-121",
    "parent": {
       "id": "2",
       "name": "A2-12",
       "parent": {
           ...,
           "parent": {
               ...
           }
       }
    }
}

How can I fetch all the parents of a sub organization in a tree?

Used packages:

"typeorm": "^0.3.16"
"@nestjs/typeorm": "^9.0.1"
1

There are 1 best solutions below

0
Pedram On

I had the same problem. For now, I've used a recursive function to get by.

function getAllNestedParents(obj: any): any[] {
    if (!obj?.parent) {
      return [];
    }

    const parents: any[] = [obj.parent];
    return parents.concat(getAllNestedParents(obj.parent));
  }

Please replace the any types with your use case.