ZBLOG

prisma 同时使用 mysql 和 mongodb 例子

Prisma是一个ORM框架,可以为不同的数据库提供统一的API。以下是一个使用Prisma同时连接MySQL和MongoDB的例子:

  1. 安装Prisma CLI

首先,需要安装Prisma CLI,并创建一个新的Prisma项目。

  1. npm i prisma -g
  2. prisma init myproject
  1. 配置MySQL连接

进入Prisma项目目录,在prisma/schema.prisma文件中添加MySQL数据库连接信息。

  1. datasource mysql {
  2. provider = "mysql"
  3. url = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
  4. }

替换USERPASSWORDHOSTPORTDATABASE为实际的MySQL连接信息。

  1. 创建MySQL数据模型

prisma/schema.prisma文件中定义MySQL数据库的数据模型。

  1. model User {
  2. id Int @id @default(autoincrement())
  3. name String
  4. email String @unique
  5. posts Post[]
  6. }
  7. model Post {
  8. id Int @id @default(autoincrement())
  9. title String
  10. content String?
  11. authorId Int
  12. author User @relation(fields: [authorId], references: [id])
  13. }

这里定义了两个模型:User和Post,User拥有多个Post。其中,@id表示该字段是主键,@default(autoincrement())表示自增长。

  1. 运行Prisma migration

在终端中运行以下命令,生成并执行MySQL数据库迁移脚本。

  1. npx prisma migrate save --name init --preview-feature
  2. npx prisma migrate up --preview-feature

这将在MySQL数据库中创建User和Post表。

  1. 配置MongoDB连接

prisma/schema.prisma文件中添加MongoDB数据库连接信息。

  1. datasource mongo {
  2. provider = "mongodb"
  3. url = "mongodb://USER:PASSWORD@HOST:PORT/DATABASE"
  4. }

替换USERPASSWORDHOSTPORTDATABASE为实际的MongoDB连接信息。

  1. 创建MongoDB数据模型

prisma/schema.prisma文件中定义MongoDB数据库的数据模型。

  1. model Log {
  2. id String @id @default(uuid())
  3. level String
  4. message String?
  5. createdAt DateTime @default(now())
  6. }

这里定义了一个模型:Log。其中,@id表示该字段是主键,@default(uuid())表示使用UUID作为默认值。

  1. 运行Prisma migration

在终端中运行以下命令,生成并执行MongoDB数据库迁移脚本。

  1. npx prisma migrate save --name init-mongo --preview-feature
  2. npx prisma migrate up --preview-feature

这将在MongoDB数据库中创建Log集合。

  1. 使用Prisma API操作不同的数据库

现在可以使用Prisma API操作MySQL和MongoDB数据库了。以下是一个简单的例子:

  1. const { PrismaClient } = require('@prisma/client')
  2. const prisma = new PrismaClient()
  3. async function main() {
  4. // 使用MySQL
  5. const user = await prisma.user.create({
  6. data: {
  7. name: 'Alice',
  8. email: 'alice@example.com',
  9. posts: {
  10. create: {
  11. title: 'Hello, World!',
  12. content: 'This is my first post.'
  13. }
  14. }
  15. },
  16. include: { posts: true }
  17. })
  18. console.log(user)
  19. // 使用MongoDB
  20. const log = await prisma.log.create({
  21. data: {
  22. level: 'info',
  23. message: 'Hello, MongoDB!'
  24. }
  25. })
  26. console.log(log)
  27. }
  28. main()
  29. .catch(err => console.error(err))
  30. .finally(async () => await prisma.$disconnect())

这里使用prisma.user.create()方法向MySQL数据库中创建一个用户和一篇文章,并通过include选项将文章也返回。然后使用prisma.log.create()方法向MongoDB数据库中创建一条日志。最后,调用prisma.$disconnect()方法关闭连接。

以上就是一个使用Prisma同时连接MySQL和MongoDB的例子。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=2269

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?