在 MongoDB 上为多对多关系设置 Prisma 模式时遇到困难

问题描述 投票:0回答:1

我正在尝试使用 PrismaORM 和 MongoDB 创建模式,但我面临着在 User 和 Post 模型之间建立多对多关系的问题。我的目标是在这些模型中的 favoritesfavoriteBy 字段之间建立关系。然而,在使用 MongoDB 时,我在 Prisma 架构语法中实现此设置时遇到了错误。

Error - 解析属性“@relation”时出错:

fields
参数中定义的标量字段必须是
references
中定义的相同类型的数组。enter image description here

这是我完整的架构文件:

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

  post      Post[] @relation("UserPosts")
  favorites Post[] @relation("UserFavorites", references: [id])
}

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)

  favoritedBy User[] @relation("UserFavorites", fields: [userId], references: [id])

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

有人可以帮我解决这个问题吗?

我尝试通过多种方式使用 MongoDB 在 Prisma 模式中的 User 和 Post 模型之间建立多对多关系,并向 ChatGPT 询问错误,但找不到解决方案。希望我能在这里得到我的解决方案。

mongodb database-design many-to-many prisma database-management
1个回答
0
投票

Prisma 的文档 涵盖了这个确切的案例,并提供了一些非常好的示例,因此我建议仔细阅读它。正如文档中提到的,MongoDB 不支持隐式多对多关系,因此您要做的就是使其成为显式关系;这意味着添加一个链接表。

这是一个适合您的用例的完整示例:

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
  /// Reference the link table
  userPosts    UserPosts[]
}

model Post {
  id        String      @id @default(auto()) @map("_id") @db.ObjectId
  slug      String[]
  caption   String?
  createdAt DateTime    @default(now())
  updatedAt DateTime    @updatedAt
  /// Reference the link table
  userPosts UserPosts[]
}

/// Link table
model UserPosts {
  id     String @id @default(auto()) @map("_id") @db.ObjectId
  user   User   @relation(fields: [userId], references: [id])
  userId String @db.ObjectId
  post   Post   @relation(fields: [postId], references: [id])
  postId String @db.ObjectId
}


© www.soinside.com 2019 - 2024. All rights reserved.