簡體   English   中英

Nest js + prisma項目,服務中findUnique方法出錯

[英]Nest js + prisma project, error in findUnique method in services

當使用帶有嵌套的棱鏡時,我有疑問我做錯了什么。 我收到此錯誤

src/modules/auth/auth.service.ts:28:63 - error TS2322: Type 'UserWhereUniqueInput' is not assignable to type 'string'.
28     const user = await this.prisma.user.findUnique({ where: { email } });
                                                                 ~~~~~

  node_modules/.prisma/client/index.d.ts:1521:5
    1521     email?: string
             ~~~~~
    The expected type comes from property 'email' which is declared here on type 'UserWhereUniqueInput'
[11:50:56 PM] Found 1 error. Watching for file changes

棱鏡誤差

在 auth.service.ts

...
@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService, private prisma: PrismaService) {}

  async signIn({
    email,
    password,
  }: {
    email: Prisma.UserWhereUniqueInput;
    password: string;
  }) {
    const user = await this.prisma.user.findUnique({ where: { email } });
...

我的用戶模式是下一個

model User {
 id         Int      @id @default(autoincrement())
 email      String   @unique
 password   String
 lastName   String?
 firstName  String?
 roles      String[]
}

正在調用服務的 controller 是

...
@Post('sign-in')
  signIn(@Body() signinAuthDto: any) {
    return this.authService.signIn(signinAuthDto);
  }

我在這里添加了 any 而不是 SigninAuthDto 但它仍然失敗

export class SigninAuthDto {
  email: string;
  password: string;
}

為什么不在方法 signIn 中僅將屬性 email 的類型設為字符串? 問題是您正在嘗試將字符串 email 輸入到 object,prisma 唯一輸入。

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService, private prisma: PrismaService) {}

  async signIn({
    email,
    password,
  }: {
    email: string;
    password: string;
  }) {
    const user = await this.prisma.user.findUnique({ where: { email } });

希望這會有所幫助!

我也遇到過類似的情況。 答案是讓 user 成為一個獨特的領域。 您可以通過在 schema.prisma 文件中的 email 前面添加 @unique 輕松做到這一點

model User {
 id       String @id @default(cuid())
 name     String
 email    String @unique
 username String
 password String
}

這告訴 prisma 將 email 添加到錯誤消息中提到的 UserWhereUniqueInput 類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM