Nestjs 和 TypeORM 无法正常使用 findOne

Nest JS & TypeORM cannot use findOne properly

我正在尝试获取基于 id 的用户实例(其他属性如 email 也是如此。在服务内部,这是我的代码:

@Injectable()
export class UserService {
  @InjectRepository(User)
  private readonly repository: Repository<User>;

  async findOne(id: number): Promise<User> {
    const user = await this.repository.findOne(id);
    return user;
  }
}

我的用户实体是:

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

  @Column({ type: 'varchar', length: 120 })
  public name: string;

  @Column({ type: 'varchar', length: 120 })
  public email: string;
}

问题是我总是收到这个错误: src/api/user/user.service.ts - error TS2559: Type 'number' has no properties in common with type 'FindOneOptions<User>'.

其他方法如 getAll 工作正常:

public getAllUsers(): Promise<User[]> {
  return this.repository.find();
}

您使用的是最新版本的typeorm吗?然后将其降级为 typeorm@0.2,因为 @nestjs/typeorm@8.0 可能还不支持最新版本。您可以在此处阅读 typeorm@0.3 的更改:https://github.com/typeorm/typeorm/releases/tag/0.3.0

check-in 你的 package.json 文件并用这个 "typeorm": "^0.2.34"

替换你的 typeorm 版本