Prisma ORM 与 MongoDB 快速入门
MongoDB 是一款流行的 NoSQL 文档数据库。本指南将教你如何从零开始创建一个新的 TypeScript 项目,使用 Prisma ORM 将其连接到 MongoDB,并生成 Prisma 客户端,以便轻松、安全地访问你的数据库。
¥MongoDB is a popular NoSQL document database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to MongoDB using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database.
Prisma ORM v7 即将支持 MongoDB。同时,在使用 MongoDB 时,请使用 Prisma ORM v6.19(最新的 v6 版本)。
¥MongoDB support for Prisma ORM v7 is coming in the near future. In the meantime, please use Prisma ORM v6.19 (the latest v6 release) when working with MongoDB.
本指南使用 Prisma ORM v6.19 以确保与 MongoDB 完全兼容。
¥This guide uses Prisma ORM v6.19 to ensure full compatibility with MongoDB.
先决条件
¥Prerequisites
-
你的系统中已安装 Node.js 使用支持的版本
¥Node.js installed in your system with the supported version
-
可通过连接字符串访问的 MongoDB 数据库
¥A MongoDB database accessible via connection string
1. 创建一个新项目
¥ Create a new project
创建一个项目目录并导航到它:
¥Create a project directory and navigate into it:
mkdir hello-prisma
cd hello-prisma
初始化 TypeScript 项目:
¥Initialize a TypeScript project:
npm init -y
npm install typescript tsx @types/node --save-dev
npx tsc --init
2. 安装所需依赖
¥ Install required dependencies
安装此快速入门所需的软件包:
¥Install the packages needed for this quickstart:
npm install prisma@6.19 @types/node --save-dev
npm install @prisma/client@6.19 dotenv
这是 Prisma ORM v6 的最新稳定版本,完全支持 MongoDB。Prisma ORM v7 即将支持 MongoDB。
¥This is the latest stable version of Prisma ORM v6 that fully supports MongoDB. MongoDB support for Prisma ORM v7 is coming soon.
你还可以安装 prisma@6 和 @prisma/client@6 以自动获取最新的 v6 版本。
¥You can also install prisma@6 and @prisma/client@6 to automatically get the latest v6 release.
以下是每个包的功能:
¥Here's what each package does:
-
prisma- 用于运行prisma init、prisma db push和prisma generate等命令的 Prisma CLI¥
prisma- The Prisma CLI for running commands likeprisma init,prisma db push, andprisma generate -
@prisma/client- 用于查询数据库的 Prisma 客户端库¥
@prisma/client- The Prisma Client library for querying your database -
dotenv- 从你的.env文件加载环境变量¥
dotenv- Loads environment variables from your.envfile
MongoDB 不需要驱动程序适配器,因为 Prisma ORM 直接连接到 MongoDB。
¥MongoDB doesn't require driver adapters since Prisma ORM connects directly to MongoDB.
3. 配置 ESM 支持
¥ Configure ESM support
更新 tsconfig.json 以兼容 ESM:
¥Update tsconfig.json for ESM compatibility:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}
更新 package.json 以启用 ESM:
¥Update package.json to enable ESM:
{
"type": "module",
}
4. 初始化 Prisma ORM
¥ Initialize Prisma ORM
你现在可以通过添加 npx 前缀来调用 Prisma CLI:
¥You can now invoke the Prisma CLI by prefixing it with npx:
npx prisma
接下来,使用以下命令创建 Prisma 模式 文件来设置 Prisma ORM 项目:
¥Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:
npx prisma init --datasource-provider mongodb --output ../generated/prisma
此命令执行以下几项操作:
¥This command does a few things:
-
创建一个名为
prisma/的文件,其中包含用于数据库连接和模式模型的schema.prisma文件¥Creates a
prisma/directory with aschema.prismafile for your database connection and schema models -
在根目录中创建一个用于环境变量的
.env文件¥Creates a
.envfile in the root directory for environment variables -
创建一个用于 Prisma 配置的
prisma.config.ts文件¥Creates a
prisma.config.tsfile for Prisma configuration
当你在本指南的后续部分运行 npx prisma generate 时,Prisma 客户端将在 generated/prisma/ 目录中生成。
¥Prisma Client will be generated in the generated/prisma/ directory when you run npx prisma generate later in this guide.
生成的 prisma.config.ts 文件如下所示:
¥The generated prisma.config.ts file looks like this:
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
engine: "classic",
datasource: {
url: env('DATABASE_URL'),
},
})
将 dotenv 添加到 prisma.config.ts,以便 Prisma 可以从 .env 文件加载环境变量:
¥Add dotenv to prisma.config.ts so that Prisma can load environment variables from your .env file:
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
engine: "classic",
datasource: {
url: env('DATABASE_URL'),
},
})
生成的 schema 使用带有自定义输出路径的 ESM 优先的 prisma-client 生成器:
¥The generated schema uses the ESM-first prisma-client generator with a custom output path:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
使用 MongoDB 连接字符串更新 .env 文件:
¥Update your .env file with your MongoDB connection string:
DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb"
将 username、password、cluster 和 mydb 替换为你的实际 MongoDB 凭据和数据库名称。你可以从 MongoDB 阿特拉斯 或你的 MongoDB 部署中获取连接字符串。
¥Replace username, password, cluster, and mydb with your actual MongoDB credentials and database name. You can get your connection string from MongoDB Atlas or your MongoDB deployment.
5. 定义你的数据模型
¥ Define your data model
打开 prisma/schema.prisma 文件并添加以下模型:
¥Open prisma/schema.prisma and add the following models:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
posts Post[]
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
6. 将 schema 推送到 MongoDB
¥ Push your schema to MongoDB
MongoDB 不支持像关系型数据库那样的迁移。你可以使用 db push 来同步你的模式:
¥MongoDB doesn't support migrations like relational databases. Instead, use db push to sync your schema:
npx prisma db push
这个命令:
¥This command:
-
根据你的模式在 MongoDB 中创建集合
¥Creates the collections in MongoDB based on your schema
-
自动生成 Prisma 客户端
¥Automatically generates Prisma Client
与关系型数据库不同,MongoDB 使用灵活的模式。db push 命令确保你的 Prisma 架构反映在数据库中,而无需创建迁移文件。
¥Unlike relational databases, MongoDB uses a flexible schema. The db push command ensures your Prisma schema is reflected in your database without creating migration files.
7. 实例化 Prisma 客户端
¥ Instantiate Prisma Client
现在你已安装所有依赖,可以实例化 Prisma Client 了:
¥Now that you have all the dependencies installed, you can instantiate Prisma Client:
import "dotenv/config";
import { PrismaClient } from '../generated/prisma/client'
const prisma = new PrismaClient()
export { prisma }
8. 编写你的第一个查询
¥ Write your first query
创建 script.ts 文件以测试你的设置:
¥Create a script.ts file to test your setup:
import { prisma } from './lib/prisma'
async function main() {
// Create a new user with a post
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: {
title: 'Hello World',
content: 'This is my first post!',
published: true,
},
},
},
include: {
posts: true,
},
})
console.log('Created user:', user)
// Fetch all users with their posts
const allUsers = await prisma.user.findMany({
include: {
posts: true,
},
})
console.log('All users:', JSON.stringify(allUsers, null, 2))
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
运行脚本:
¥Run the script:
npx tsx script.ts
你应该在控制台中看到已创建的用户以及所有用户!
¥You should see the created user and all users printed to the console!
9. 探索你的数据
¥ Explore your data
你可以使用 MongoDB 阿特拉斯、MongoDB shell 或 MongoDB Compass 查看和管理你的数据。
¥You can use MongoDB Atlas, the MongoDB shell, or MongoDB Compass to view and manage your data.
Prisma 工作室 目前不支持 MongoDB。未来版本可能会添加此功能。请参阅 Prisma 支持的数据库 Studio 了解更多信息。
¥Prisma Studio does not currently support MongoDB. Support may be added in a future release. See Databases supported by Prisma Studio for more information.
下一步
¥Next steps
你已成功设置 Prisma ORM。接下来你可以探索以下内容:
¥You've successfully set up Prisma ORM. Here's what you can explore next:
-
了解更多关于 Prisma 客户端的信息:探索 Prisma 客户端 API 的高级查询、筛选和关联功能
¥Learn more about Prisma Client: Explore the Prisma Client API for advanced querying, filtering, and relations
-
数据库迁移:了解 Prisma 迁移,以便演进你的数据库模式
¥Database migrations: Learn about Prisma Migrate for evolving your database schema
-
性能优化:Discover 查询优化技巧
¥Performance optimization: Discover query optimization techniques
-
构建完整应用:查看我们的 框架指南,了解如何将 Prisma ORM 与 Next.js、Express 等集成。
¥Build a full application: Check out our framework guides to integrate Prisma ORM with Next.js, Express, and more
-
加入社区:通过 Discord 与其他开发者连接
¥Join the community: Connect with other developers on Discord
故障排除
¥Troubleshooting
Error in connector: SCRAM failure: Authentication failed.
如果你看到 Error in connector: SCRAM failure: Authentication failed. 错误消息,你可以通过 adding ?authSource=admin 在连接字符串末尾指定身份验证的源数据库。
¥If you see the Error in connector: SCRAM failure: Authentication failed. error message, you can specify the source database for the authentication by adding ?authSource=admin to the end of the connection string.
Raw query failed. Error code 8000 (AtlasError): empty database name not allowed.
如果你看到 Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed. 错误消息,请确保将数据库名称附加到数据库 URL。你可以在此 GitHub 问题 中找到更多信息。
¥If you see the Raw query failed. Code: unknown. Message: Kind: Command failed: Error code 8000 (AtlasError): empty database name not allowed. error message, be sure to append the database name to the database URL. You can find more info in this GitHub issue.
更多信息
¥More info