【问题标题】:Nest JS & TypeORM cannot use findOne properlyNest JS & TypeORM 无法正确使用 findOne
【发布时间】:2022-07-05 02:10:30
【问题描述】:

我正在尝试获取基于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&lt;User&gt;'.

getAll 等其他方法也可以正常工作:

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

【问题讨论】:

    标签: javascript nestjs typeorm


    【解决方案1】:

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

    【讨论】:

    • 这确实修复了它,谢谢!
    【解决方案2】:

    签入您的package.json 文件并将您的typeorm 版本替换为"typeorm": "^0.2.34"

    【讨论】:

      【解决方案3】:

      typeorm 中有一些重大更改。

      findOne(id);
      

      现在改为

      findOneBy({
      id: id // where id is your column name
      })
      

      find() 现在是

      find({
        select: {
          id: true,
          email: true,
          password: true,
        },
      });
      

      请查看this link了解更多信息。

      【讨论】:

        猜你喜欢
        • 2022-01-04
        • 2021-10-12
        • 2021-05-29
        • 1970-01-01
        • 2022-01-23
        • 2021-06-11
        • 2023-02-03
        • 2020-12-11
        • 2022-01-23
        相关资源
        最近更新 更多