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

使用MongoDB时Prisma是否自动创建多对多关系集合?

Prisma + MongoDB 多对多关系集合创建问题

在你给出的Prisma Schema定义下,使用MongoDB时,Prisma会自动创建用于记录Post和Category多对多关系的_CategoryToPost集合,无需你手动创建。

当你执行prisma db push(MongoDB场景更推荐该命令)或prisma migrate dev这类将Schema同步到数据库的操作时,Prisma会自动生成并维护这个连接集合,用来存储两者的关联数据,对应你提供的示意图:

多对多关系集合示意图

你的完整Schema定义如下:

model User {
  id      Int      @id @default(autoincrement())
  email   String   @unique
  name    String?
  role    Role     @default(USER)
  posts   Post[]
  profile Profile?
}

model Profile {
  id     Int    @id @default(autoincrement())
  bio    String
  user   User   @relation(fields: [userId], references: [id])
  userId Int    @unique
}

model Post {
  id         Int        @id @default(autoincrement())
  createdAt  DateTime   @default(now())
  title      String
  published  Boolean    @default(false)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   Int
  categories Category[] @relation(references: [id])
}

model Category {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[] @relation(references: [id])
}

enum Role {
  USER
  ADMIN
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:10:25