typescriptgraphqlnestjstypeormtree-structure

How can I filter data without loading it first?


I am using nestjs-typeorm and want to filter out nested data based on some reference. The code loads the whole database first and then filters the required result. How can I filter out the required data without loading entire table of the database making it more efficient and fast?

service.ts

public async uploadedFiles(fileReferenceParams: ReferenceFilterParams): Promise<UploadedFilesEntity[]> {
    try {
      const manager = getManager();
      const trees = await manager.getTreeRepository(UploadedFilesEntity).findTrees();
      this.uploadedFilesRepository.createQueryBuilder()
      const rootFiles = trees.filter(tree => ( tree.isDeleted==false||null && tree.referenceID == fileReferenceParams.referenceID && tree.referenceType == fileReferenceParams.referenceType));
      return rootFiles;
    } catch (error) {
      return error;
    }
  }


Solution

  • You can use the createQueryBuilder of TypeORM to filter in SQL without a post query filter.

    const trees = await this.repository.createQueryBuilder('tree')
        .where('tree.isDeleted IS FALSE OR NULL')
        .andWhere('tree.referenceID = :referenceId', { referenceId: fileReferenceParams.referenceID })
        .andWhere('tree.referenceType = :referenceType', { referenceType: fileReferenceParams.referenceType })
        .getMany();
    

    Learn more about query builder on the TypeORM documentation to execute query with SQL search parameters