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

NestJS中无法通过userId查询Prisma Schema的书签数据

问题:通过用户ID查询Bookmark表数据失败

问题说明

想用用户ID查询该用户的所有书签,但直接用where: { id: userId }是按书签ID查询,不符合需求。尝试通过Bookmark模型的userId字段过滤时报错。

Prisma模型定义

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  email String @unique
  hash  String

  firstName String?
  lastName  String?

  bookmarks Bookmark[]

  @@map("users")
}

model Bookmark {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  title       String
  description String?
  link        String

  userId Int
  user   User @relation(fields: [userId], references: [id])

  @@map("bookmarks")
}

尝试的查询代码

getBookmarksByUserId(userId: number) {
    return this.prisma.bookmark.findMany({
        where: {
            userId: userId
        }
    });
}

报错信息

Unknown arg `userId` in where.userId for type BookmarkWhereInput. Did you mean `id`? Available args:
type BookmarkWhereInput {
  AND?: BookmarkWhereInput | List<BookmarkWhereInput>
  OR?: List<BookmarkWhereInput>
  NOT?: BookmarkWhereInput | List<BookmarkWhereInput>
  id?: IntFilter | Int
  createdAt?: DateTimeFilter | DateTime
  updatedAt?: DateTimeFilter | DateTime
  title?: StringFilter | String
  description?: StringNullableFilter | String | Null
  link?: StringFilter | String
}

解决方法

  1. 重新生成Prisma Client
    你修改了Prisma模型定义(添加了userId字段和关联),但没有重新生成Prisma客户端,导致类型定义没有更新。执行以下命令:

    npx prisma generate
    

    重新生成后,BookmarkWhereInput就会包含userId字段,原查询代码就能正常运行。

  2. 通过User模型关联查询(可选)
    也可以通过User模型的关联关系查询用户的书签:

    async getBookmarksByUserId(userId: number) {
        const user = await this.prisma.user.findUnique({
            where: { id: userId },
            include: { bookmarks: true }
        });
        return user?.bookmarks || [];
    }
    

内容的提问来源于stack exchange,提问作者yanir midler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:50:21