![](/img/trans.png)
[英]how to use typescript typeorm in vanilla js, nest.js?
[英]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
typeorm
有一些重大變化。 我不建議降級,而是檢查最新的方法。
findOne(id);
現在改為
findOneBy({
id: id // where id is your column name
})
而find()
現在是
find({
select: {
id: true,
email: true,
password: true,
},
});
請檢查此鏈接以獲取更多信息。
簽入您的package.json
文件並將您的 typeorm 版本替換為"typeorm": "^0.2.34"
問題是 typeorm 版本,嘗試 typeorm 版本 0.2.25,它會工作
實際上,您不需要降級typeorm
package。 剛剛更改為findOne
:
async findOne(id: number): Promise<User> {
const user = await this.repository.findOne({
where: { id }
});
return user;
}
也有人可以解釋一下。 我正在看一段代碼
async findOne(id: FindOneOptions<User>): Promise<User> {
const user = await this.repository.findOne(id)
return user;
}
這個做完了。 雖然它不起作用但是為什么我們將數字id聲明為FindOneOptions<User>
findOne(id) 簽名被丟棄。 請改用以下語法:
const user = await userRepository.findOneBy({
id: id // where id is your column name
})
根據最新版本的Typeorm,findOne 表達式已更改為如上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.