You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS用nestjs-paginate+TypeORM关联分页时出现databaseName读取错误

NestJS + nestjs-paginate + TypeORM 关联分页报错解决

错误原因

这个Cannot read properties of undefined (reading 'databaseName')错误,核心是TypeORM的查询构建器无法获取关联实体的数据库元信息,大概率是关联实体未正确注册、分页配置的关联参数有误,或者依赖版本不兼容导致的。

解决步骤

1. 检查实体关联与注册

确保Customer实体的关联装饰器配置正确,且关联的PhoneNumber、Dealer实体已在TypeORM模块中注册:

Customer实体示例:

// customer.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from 'typeorm';
import { PhoneNumber } from './phone-number.entity';
import { Dealer } from './dealer.entity';

@Entity()
export class Customer {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToMany(() => PhoneNumber, phone => phone.customer)
  phoneNumbers: PhoneNumber[];

  @ManyToOne(() => Dealer, dealer => dealer.customers)
  dealer: Dealer;
}

TypeORM模块注册示例:

// app.module.ts
@Module({
  imports: [
    TypeOrmModule.forRoot({
      // 其他数据库配置
      entities: [Customer, PhoneNumber, Dealer], // 必须包含所有关联实体
    }),
  ],
})
export class AppModule {}

2. 修正分页配置的关联参数

在CustomerService的分页方法中,确保relations选项正确指定关联,若要返回关联实体的具体字段,需用点语法声明:

正确的分页配置示例:

// customer.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Customer } from './customer.entity';
import { paginate, PaginateQuery } from 'nestjs-paginate';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(Customer)
    private readonly customerRepository: Repository<Customer>,
  ) {}

  async findAll(query: PaginateQuery) {
    return paginate(query, this.customerRepository, {
      sortableColumns: ['id', 'name', 'dealer.name'],
      relations: ['phoneNumbers', 'dealer'], // 明确指定要加载的关联
      select: ['id', 'name', 'phoneNumbers.number', 'dealer.name'], // 关联字段用点语法
    });
  }
}

3. 验证Repository注入正确性

确保CustomerService中注入的是TypeORM原生的Repository,而非自定义的错误类型,避免查询构建器初始化异常。

4. 适配依赖版本

若以上配置均无问题,可能是nestjs-paginate与TypeORM版本不兼容,尝试更新到最新稳定版:

npm update nestjs-paginate typeorm @nestjs/typeorm

内容的提问来源于stack exchange,提问作者Ali Parlatti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:31:02