Skip to main content

使用 JavaScript 和 MongoDB 创建 Prisma 架构

更新 Prisma 架构

¥Update the Prisma schema

打开 prisma/schema.prisma 文件并将默认内容替换为以下内容:

¥Open the prisma/schema.prisma file and replace the default contents with the following:

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 等关系数据库相比,模式的设置方式也存在一些细微的差异。

¥There are also a number of subtle differences in how the schema is setup when compared to relational databases like PostgreSQL.

例如,基础 ID 字段名称始终为 _id,并且必须与 @map("_id") 进行映射。

¥For example, the underlying ID field name is always _id and must be mapped with @map("_id").

欲了解更多信息,请查看 MongoDB 架构参考

¥For more information check out the MongoDB schema reference.