跳到主要內容

內省

Prisma ORM 透過取樣給定資料庫中儲存的資料並推斷該資料的結構描述,來內省 MongoDB 結構描述。

為了說明內省的目的,本指南將協助您從頭設定 MongoDB。但是,如果您已經有 MongoDB 資料庫,請隨時跳到專案中的初始化 Prisma ORM

設定您的資料庫

為了實際了解此操作,首先建立一個包含 2 個集合的 blog 資料庫:UserPost。我們推薦使用 MongoDB Compass 來進行設定

Create a blog database using Compass

首先,將使用者新增到我們的 User 集合

Create a user within the User collection

接下來,將一些貼文新增到我們的 Post 集合。重要的是 userId 中的 ObjectID 與您上面建立的使用者相符。

Create some posts within the Post collection

初始化 Prisma ORM

現在您已經有一個 MongoDB 資料庫,下一步是建立一個新專案並初始化 Prisma ORM

mkdir blog
cd blog
npm init -y
npm install -D prisma
npx prisma init

初始化 Prisma ORM 將建立一個 prisma/schema.prisma 檔案。編輯此檔案以使用 MongoDB

prisma/schema.prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

接下來,您需要調整您的 .env 檔案,將 DATABASE_URL 指向您的 MongoDB 資料庫

使用 Prisma ORM 內省 MongoDB

您現在已準備好進行內省。執行以下命令來內省您的資料庫

npx prisma db pull

此命令會內省我們的資料庫,並將推斷的結構描述寫入您的 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
title String
userId String @db.ObjectId
}

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
}

調整結構描述

為了能夠使用 Prisma Client 加入資料,您可以將 @relation 屬性新增到我們的模型中

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
title String
userId String @db.ObjectId
user User @relation(fields: [userId], references: [id])
}

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
posts Post[]
}
提示

我們正在積極開發 MongoDB 內省功能。請在 此 issue 中提供有關此功能的意見回饋。

這樣一來,您就可以準備好產生 Prisma Client 了。