使用 TypeScript 和 MongoDB 建立 Prisma schema
更新 Prisma schema
開啟 prisma/schema.prisma 檔案,並用以下內容替換預設內容
prisma/schema.prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
slug String @unique
title String
body String
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
comments Comment[]
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
address Address?
posts Post[]
}
model Comment {
id String @id @default(auto()) @map("_id") @db.ObjectId
comment String
post Post @relation(fields: [postId], references: [id])
postId String @db.ObjectId
}
// Address is an embedded document
type Address {
street String
city String
state String
zip String
}
與 PostgreSQL 等關係型資料庫相比,schema 的設定方式也存在一些細微差別。
例如,底層 ID 欄位名稱始終為 _id,並且必須使用 @map("_id") 進行對映。
更多資訊請檢視 MongoDB schema 參考。