MongoDB Using Prisma in NestJS

오픈소스·2023년 4월 10일
0

MongoDB with Prisma

목록 보기
4/4
post-thumbnail

Install Prisma CLI & Initialize Prisma in application

$ npm install prisma --save-dev
$ prisma init

✔ Your Prisma schema was created at prisma/schema.prisma
  You can now open it in your favorite editor.

warn You already have a .gitignore file. Don't forget to add `.env` in it to not commit any private information.

Next steps:
1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started
2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql, sqlite, sqlserver, mongodb or cockroachdb.
3. Run prisma db pull to turn your database schema into a Prisma schema.
4. Run prisma generate to generate the Prisma Client. You can then start querying your database.

More information in our documentation:
https://pris.ly/d/getting-started

Connect your database

  • .env 화일에서 DATABASE_URL 수정
DATABASE_URL="mongodb://${MONGO_USER}:${MONGO_PW}@${MONGO_HOST}:${MONGO_PORT}/${MONGO_DB}?authSource=admin"

https://www.prisma.io/docs/concepts/database-connectors/mongodb

Define the schema

  • prisma/schema.prisma 화일에 모델 추가
...
model User {
  id              String   @id @default(auto()) @map("_id") @db.ObjectId
  provider        String
  provider_id     String
  username        String?
  email           String?
  profileImage    String?
  thumbnailImage  String?
  accessToken     String
  refreshToken    String?
  createdAt       DateTime  @default(now())
  updatedAt       DateTime  @updatedAt
  chats           Chat[]
  @@unique([provider, provider_id])
}

model Chat {
  id        String    @id @default(auto()) @map("_id") @db.ObjectId
  message   String
  createdAt DateTime  @default(now())
  sender    User      @relation(fields: [senderId], references: [id])
  senderId  String    @db.ObjectId
}

Sync schema with database

$ npx prisma db push
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": MongoDB database "chat" at "127.0.0.1:27017"
Applying the following changes:

[+] Collection `User`
[+] Collection `Chat`
[+] Unique index `User_provider_provider_id_key` on ({"provider":1,"provider_id":1})


🚀  Your database indexes are now in sync with your Prisma schema. Done in 76ms

✔ Generated Prisma Client (4.12.0 | library) to ./node_modules/@prisma/client in 384ms

Troubleshooting1

https://www.prisma.io/docs/guides/migrate/prototyping-schema-db-push

$ npx prisma migrate dev --name initial-state
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": MongoDB database "chat" at "127.0.0.1:27017"

Error: The "mongodb" provider is not supported with this command. For more info see https://www.prisma.io/docs/concepts/database-connectors/mongodb
   0: migration_core::state::DevDiagnostic
             at migration-engine/core/src/state.rs:269

참고)


Install and generate Prisma Client

$ npm install @prisma/client
$ npx prisma generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma

✔ Generated Prisma Client (4.12.0 | library) to ./node_modules/@prisma/client in 38ms
You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client
\```
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
\```
$ nest g s prisma
CREATE src/prisma/prisma.service.spec.ts (460 bytes)
CREATE src/prisma/prisma.service.ts (90 bytes)
UPDATE src/app.module.ts (1137 bytes)

src/prisma/prisma.service.ts
(https://docs.nestjs.com/recipes/prisma#use-prisma-client-in-your-nestjs-services)

import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

Troubleshooting2

Invalid `this.prisma.user.create()` invocation in
/Users/youngkiu/src/nestjs-kakaologin/src/user/user.service.ts:20:29

  17 
  18 async create(data: Prisma.UserCreateInput): Promise<User> {
  19   // https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb/querying-the-database-typescript-mongodb#write-data-into-the-database20   return this.prisma.user.create(
Prisma needs to perform transactions, which requires your MongoDB server to be run as a replica set. https://pris.ly/d/mongodb-replica-set

위와 같은 에러가 나온다면, https://velog.io/@youngkiu/MongoDB-Replica-Set-for-Prisma 를 참조하세요.


모든 문제를 해결하고, PrismaService를 이용하여, UserService를 적절히 구현하였을 때, 다음과 같이 MongoDB에 데이타가 추가됨을 확인할 수 있었다.

https://nestjs-kakaologin.onrender.com/ (cold start시 좀 더 기다리면 나타납니다.)

참조)

0개의 댓글