使用Prisma ORM在MongoDB中配置User与Post多对多关系报错求助
解决Prisma ORM中MongoDB的User与Post多对多收藏关系配置错误
错误原因分析
你遇到的错误是因为多对多关系的关联字段类型不匹配:在Post模型的favoritedBy关联中,你指定了单个String类型的userId作为fields参数,但多对多关系要求关联字段必须是与references目标类型(User.id是String)一致的数组类型。
修正后的完整Schema
datasource db { provider = "mongodb" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" previewFeatures = ["relationJoins"] } model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String @unique username String @unique password String profileImage String? @default("https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_640.png") bio String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt posts Post[] @relation("UserPosts") favorites Post[] @relation("UserFavorites") } model Post { id String @id @default(auto()) @map("_id") @db.ObjectId slug String[] caption String? userId String @db.ObjectId user User @relation("UserPosts", fields: [userId], references: [id], onDelete: Cascade) // 新增:存储喜欢该帖子的用户ID数组 favoriteUserIds String[] @db.ObjectId // 修正多对多关联,使用数组字段作为关联依据 favoritedBy User[] @relation("UserFavorites", fields: [favoriteUserIds], references: [id]) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt }
关键修改说明
- 新增
favoriteUserIds字段:- 在
Post模型中添加favoriteUserIds String[] @db.ObjectId,用于存储所有收藏该帖子的用户ID数组,类型与User.id完全匹配(数组形式的ObjectId字符串)。
- 在
- 修正关联配置:
Post.favoritedBy关联的fields参数改为[favoriteUserIds],确保是数组类型,与references: [id]的类型要求一致。User.favorites关联只需保持关系名称"UserFavorites"与Post.favoritedBy一致,无需额外指定references,Prisma会自动识别反向关联。
- 调整字段命名:
- 将原
User.post改为User.posts,符合复数命名规范,避免歧义。
- 将原
验证步骤
修改完成后,执行以下命令确认配置有效:
# 重新生成Prisma Client prisma generate # 将Schema同步到MongoDB prisma db push
内容的提问来源于stack exchange,提问作者Gulam Mustafa
相关产品推荐
相关产品推荐

