跳到主要內容

如何從 Mongoose 遷移到 Prisma ORM

15 分鐘

簡介

本指南將向您展示如何將應用程式從 Mongoose 遷移到 Prisma ORM。我們將使用 Mongoose Express 示例 的擴充套件版本作為 示例專案,以演示遷移步驟。

您可以在“Prisma ORM 對比 Mongoose”頁面上了解 Prisma ORM 與 Mongoose 的對比。

先決條件

在開始本指南之前,請確保您具備以下條件:

  • 您想要遷移的 Mongoose 專案
  • 已安裝 Node.js (版本 18 或更高)
  • MongoDB 資料庫
  • 對 Mongoose 和 Express.js 有基本瞭解

1. 準備遷移

1.1. 瞭解遷移過程

無論您正在構建何種應用程式或 API 層,從 Mongoose 遷移到 Prisma ORM 的步驟始終相同:

  1. 安裝 Prisma CLI
  2. 內省您的資料庫
  3. 安裝並生成 Prisma Client
  4. 逐步將 Mongoose 查詢替換為 Prisma Client

這些步驟適用於您正在構建 REST API (例如,使用 Express、Koa 或 NestJS)、GraphQL API (例如,使用 Apollo Server、TypeGraphQL 或 Nexus) 或任何其他使用 Mongoose 進行資料庫訪問的應用程式。

1.2. 設定 Prisma 配置

建立新的 Prisma schema 檔案

npx prisma init --datasource-provider mongodb --output ../generated/prisma

此命令將建立

  • 一個名為 prisma 的新目錄,其中包含一個 schema.prisma 檔案;您的 Prisma schema 指定了您的資料庫連線和模型
  • .env:專案根目錄下的一個 dotenv 檔案(如果尚不存在),用於將資料庫連線 URL 配置為環境變數

Prisma schema 目前如下所示

prisma/schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}

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

提示

為了在使用 Prisma ORM 時獲得最佳開發體驗,請參閱編輯器設定,瞭解語法高亮、格式化、自動完成以及更多很酷的功能。

使用您的 MongoDB 連線字串更新 .env 檔案中的 DATABASE_URL

DATABASE_URL="mongodb://USER:PASSWORD@HOST:PORT/DATABASE"

2. 遷移資料庫 schema

2.1. 內省您的資料庫

警告

MongoDB 是一個無模式資料庫。要在專案中逐步採用 Prisma ORM,請確保您的資料庫已填充示例資料。Prisma ORM 透過取樣儲存的資料並從資料庫中的資料推斷 schema 來內省 MongoDB schema。

執行 Prisma 的內省功能,從您現有的資料庫中建立 Prisma schema

npx prisma db pull

這將建立一個包含您的資料庫 schema 的 schema.prisma 檔案。

prisma/schema.prisma
type UsersProfile {
bio String
}

model categories {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
name String
}

model posts {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
author String @db.ObjectId
categories String[] @db.ObjectId
content String
published Boolean
title String
}

model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
email String @unique(map: "email_1")
name String
profile UsersProfile?
}

2.2. 更新關係

MongoDB 不支援不同集合之間的關係。但是,您可以使用 ObjectId 欄位型別在文件之間建立引用,或者在集合中使用 ObjectIds 陣列從一個文件引用多個文件。引用將儲存相關文件的 ID。您可以使用 Mongoose 提供的 populate() 方法來用相關文件的資料填充引用。

如下更新 posts <-> users 之間的一對多關係

  • posts 模型中現有的 author 引用重新命名為 authorId 並新增 @map("author") 屬性
  • posts 模型中新增 author 關係欄位及其 @relation 屬性,指定 fieldsreferences
  • users 模型中新增 posts 關係

您的 schema 現在應該如下所示

schema.prisma
type UsersProfile {
bio String
}

model categories {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
name String
}

model posts {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String
published Boolean
v Int @map("__v")
author String @db.ObjectId
author users @relation(fields: [authorId], references: [id])
authorId String @map("author") @db.ObjectId

categories String[] @db.ObjectId
}

model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
email String @unique(map: "email_1")
name String
profile UsersProfile?
posts posts[]
}

然後,如下更新 posts <-> categories 之間的多對多引用

  • posts 模型中將 categories 欄位重新命名為 categoryIds 並使用 @map("categories") 進行對映
  • posts 模型中新增一個新的 categories 關係欄位
  • categories 模型中新增 postIds 標量列表欄位
  • categories 模型中新增 posts 關係
  • 在兩個模型上新增一個關係標量
  • 在兩側新增 @relation 屬性,指定 fieldsreferences 引數

您的 schema 現在應該如下所示

schema.prisma
type UsersProfile {
bio String
}

model categories {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
name String
posts posts[] @relation(fields: [postIds], references: [id])
postIds String[] @db.ObjectId
}

model posts {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String
published Boolean
v Int @map("__v")

author users @relation(fields: [authorId], references: [id])
authorId String @map("author") @db.ObjectId

categories String[] @db.ObjectId
categories categories[] @relation(fields: [categoryIds], references: [id])
categoryIds String[] @map("categories") @db.ObjectId
}

model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
email String @unique(map: "email_1")
name String
profile UsersProfile?
posts posts[]
}

3. 更新您的應用程式程式碼

3.1. 安裝 Prisma Client

安裝 Prisma Client 包

npm install @prisma/client

安裝 Prisma Client 包後,生成 Prisma Client

npx prisma generate

3.2. 替換 Mongoose 查詢

開始使用 Prisma Client 替換您的 Mongoose 查詢。以下是轉換一些常見查詢的示例:

// Find one
const user = await User.findById(id);

// Create
const user = await User.create({
email: 'alice@prisma.io',
name: 'Alice'
});

// Update
await User.findByIdAndUpdate(id, {
name: 'New name'
});

// Delete
await User.findByIdAndDelete(id);

3.3. 更新您的控制器

更新您的 Express 控制器以使用 Prisma Client。例如,以下是如何更新使用者控制器:

import { prisma } from '../client'

export class UserController {
async create(req: Request, res: Response) {
const { email, name } = req.body

const result = await prisma.user.create({
data: {
email,
name,
},
})

return res.json(result)
}
}

下一步

現在您已遷移到 Prisma ORM,您可以:

  • 使用 Prisma 強大的查詢 API 新增更復雜的查詢
  • 設定 Prisma Studio 進行資料庫管理
  • 實現資料庫監控
  • 使用 Prisma 的測試實用程式新增自動化測試

更多資訊


與 Prisma 保持聯絡

透過以下方式繼續您的 Prisma 之旅: 我們活躍的社群。保持資訊暢通,積極參與,並與其他開發者協作

我們真誠地重視您的參與,並期待您成為我們社群的一員!

© . This site is unofficial and not affiliated with Prisma Data, Inc.