46-Prisma Mongodb
1. Prisma ORM
- Prisma ORM은 데이터베이스 작업을 단순화하는 오픈소스 ORM이다.
- 타입 안전성 (type safe)을 갖춘 쿼리 생성 및 스키마 마이그레이션을 지원한다.
- PostgreSQL, MySQL, SQLite등 인기 데이터베이스를 지원한다.
- Prisma Schema Langauge라는 표준화된 언어로 데이터베이스 정의를 매핑 할 수 있다.
Data Source: 데이터베이스와의 연결을 정의한다.Generator: 어떤 툴이 생성될지 정의한다. (Prisma Client 등)Models: 데이터베이스 테이블의 칼럼들을 정의한다. TypeORM의 Entity같은 정의라고 볼 수 있다.Enums: 특정 필드의 허가되는 값들을 정의한다.Relations: 모델간 관계를 설정 할 수 있다. (One to One, Many to Many등)
1.1 Prisma Schema Langauge
1.1.1 DataSource
typescript
1datasource db {2provider = "postgresql"3url = "postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public"4}
- provider는 데이터베이스 타입을 정의한다. postgresql, mysql, sqlite등
- url은 연결 URL을 정의한다.
{db_type}://{username}:{password}@{host}:{port}/{db_name}?schema={schema}
1.1.2 Generator
typescript
1generator client {2provider = 'prisma-client-js'3output = './generated/prisma-client-js'4}
- provider는 제너레이터 툴을 정의한다.
- output은 API 파일을 생성할 위치를 정의한다
1.1.3 Model
typescript
1model Comment {2id Int @id @default(autoincrement())3title String4content String5}67model Tag {8name String @id9}
- Model은 테이블 정보를 정의한다.
- Scalar, Relation, Type Modifier 등을 사용해서 테이블을 정의할 수 있다
1.1.4 Enum
typescript
1model User {2id Int @id @default(autoincrement())3email String @unique4name String?5role Role @default(USER)6}78enum Role {9USER10ADMIN11}
- TypeORM에서 다뤘던 enum 개념과 같다고 생각하면 된다.
- 특정 값만 입력되도록 유도 할 수 있다
1.1.5 Relations
typescript
1model User {2id Int @id @default(autoincrement())3name String4posts Post[]5}67model Post {8id Int @id @default(autoincrement())9title String10userId Int11user User @relation(fields: [userId], references: [id], onDelete: Cascade)12}
- Relation은 One to One, One to Many, Many to Many Relationship을 형성할 때 사용된다.
- fields에 레퍼런스로 사용할 자신의 칼럼을 입력하고 references에 상대 칼럼을 입력한다.
- onDelete, onUpdate등 attribute 정의도 가능하다
1.2 Scalar Types
| 타입 | Scalar 타입 |
|---|---|
| String | Text |
| Boolean | Boolean |
| Int | Integer |
| BigInt | BigInt |
| Float | Real/Double Precision |
| Decimal | Numeric |
| DateTime | Timestamp/ Timestamptz |
| Json | JSON/JSONB |
| Bytes | BYTEA |
1.3 Attributes
| 속성 | 설명 |
|---|---|
| @id | Primary Key |
| @default | 기본값 |
| @unique | 유니크/유일무이 값 |
| @relation | 모델 간 관계 |
| @map | 테이블의 다른 칼럼으로 매핑 |
| @updatedAt | 업데이트 순간 DateTime 기록 |
| @@id | Composite Primary Key |
| @@unique | Composite Unique Key |
| @@index | Index Keys |
1.4 Prisma Client
typescript
1genreator client {2provider = 'prisma-client-js'3}
shellscript
1$ npm install @prisma/client2$ prisma generate
- generator에 prisma client 정의
- @prisma/client 설치
- prisma generate 실행 (@prisma/client 설치시 자동 실행)
1.4.1 Prisma Client 작업 플로우

1.4.2 Prisma Client 작동 방식

1.4.3 Prisma Create
typescript
1const user = await prisma.user.create({2data: {3email: 'admin@codefactory.ai',4name: 'Code Factory',5},6})
typescript
1const createMany = await prisma.user.createMany({2data: [3{ email: '민지', email: 'minji@codefactory.ai' },4{ email: '슬기', email: 'seulgi@codefactory.ai' },5{ email: '원영', email: 'minji@codefactory.ai' }, // 중복 키6{ email: '다미', email: 'dami@codefactory.ai' },7],8skipDuplicates: true, // 원영 스킵됨9})
1.4.4 Prisma Read (1)
typescript
1const user = await prisma.user.findUniquye({2where: { email: 'minji@codefactory.ai' },3})
typescript
1const result = await prisma.user.findFirst({2where: {3email: { endsWith: 'codefactory.ai' },4},5})
1.4.5 Prisma Read (2)
typescript
1const user = await prisma.user.findMany({2where: {3email: { endsWith: 'codefactory.ai' },4},5})
typescript
1const users = await prisma.user.findMany({2where: {3OR: [4{ name: { startsWith: 'E' } },5{6AND: {7profileViews: { gt: 0 },8role: { equals: 'ADMIN' },9},10},11],12},13})
1.5 Prisma Operators
| 속성 | 설명 |
|---|---|
| equals | 같은 값 |
| not | 아닌 값 |
| in | 포함하는 값 |
| notin | 포함하지 않는 값 |
| lt | 적은 값 |
| lte | 적거나 같은 값 |
| gt | 큰 값 |
| gte | 크거나 같은 값 |
| contains | 포함하는 값 |
| search | 검색 (Full Text Search) |
| startWith | 시작하는 값 |
| endsWith | 끝나는 값 |
| AND | && |
| OR | || |
| NOT | 아닌 값 |
1.5.1 Prisma Read 필드 선택하기
typescript
1const getUser = await prisma.user.findUnique({2where: { id: 22 },3select: {4email: true,5name: true,6},7})
email과 name 칼럼만 선택
1.5.2 Prisma Read Relation 포함하기
typescript
1const users = await prisma.user.findMany({2include: {3posts: {4select: { title: true },5},6},7})
user 값에 post 관계 포함해서 반환
1.5.3 Relation Filtering Some
typescript
1const result = await prisma.user.findMany({2where: {3post: {4some: {5content: { contains: 'Code Factory' },6},7},8},9})
Code Factory를 content에 포함하고 있는 post가 존재하는 user를 모두 가져옴
1.5.4 Relation Filtering Every
typescript
1const result = await prisma.user.findMany({2where: {3post: {4every: { published: true },5},6},7})
관련된 post의 published가 모두 true인 user를 모두 가져옴
1.5.5 Relation Filtering None
typescript
1const result = await prisma.user.findMany({2where: {3post: {4none: { published: true },5},6},7})
관련된 post의 published가 모두 true가 아닌 User를 모두 가져옴
1.5.6 Relation Filtering Is
typescript
1const result = await prisma.user.findMany({2where: {3user: {4is: { name: 'Code Factory' },5},6},7})
name 필드가 Code Factory인 post를 모두 가져옴
1.5.7 Relation Filtering IsNot
typescript
1const result = await prisma.user.findMany({2where: {3user: {4isNot: { name: 'Code Factory' },5},6},7})
name 필드가 Code Factory가 아닌 User를 모두 가져옴
1.5.8 Update
typescript
1const updateUser = await prisma.user.update({2where: { email: 'test@codefactory.ai' },3data: { name: '민지' },4})
사용자의 name 필드를 ‘민지’로 변경
1.5.9 Delete
typescript
1const deleteUser = await prisma.user.delete({2where: { email: 'test@codefactory.ai' },3})
email이 test@codefactory.ai인 사용자를 삭제
1.5.10 Relationship One to One
typescript
1model User {2id Int @id @default(autoincrement())3profile Profile @relation(fields: [profileId], references: [id])4profileId Int @unique // 필수 (1:1이니까ㅣ 당연히)5}67model Profile {8id Int @id @default(autoincrement())9user User? // nullable만 가능10}
typescript
1model User {2id Int @id @default(autoincrement())3profile Profile? @relation(fields: [profileId], references: [id])4profileId Int? @unique // Optional 생성 가능5}67model Profile {8id Int @id @default(autoincrement())9user User?10}
1.5.11 Relationship One to Many
typescript
1model User {2id Int @id @default(autoincrement())3posts Post[]4}56model Post {7id Int @id @default(autoincrement())8author User @relation(fields: [authorId], references: [id])9authorId Int10}
1.5.12 Relationship Many to Many
typescript
1model Post {2id Int @id @default(autoincrement())3title String4categories CategoriesOnPosts[]5}67model Category {8id Int @id @default(autoincrement())9name String10posts CategoriesOnPosts[]11}1213model CategoriesOnPosts {14post Post @relation(fields: [postId], references: [id])15postId Int16category Category @relation(fields: [categoryId], references: [id])17categoryId Int18assignedAt DateTime @default(now())19assignedBy String20@@id([postId, categoryId])21}
typescript
1model Post {2id Int @id @default(autoincrement())3title String4categories Category[]5}67model Category {8id Int @id @default(autoincrement())9name String10posts Post[]11}
1.6 Aggregate Function
| 함수 | 설명 |
|---|---|
_avg | 평균 |
_count | 개수 |
_sum | 합계 |
_min | 최소 값 |
_max | 최대 값 |
1.6.1 Aggregate
typescript
1const aggregations = await prisma.user.aggregate({2_avg: { age: true },3})
1.6.2 Raw Query
typescript
1const result = await prisma.$queryRaw('SELECT * FROM User')
1.6.3 Migration
shellscript
1# prisma migrate dev > 마이그레이션 파일 생성 (자동)2prisma migrate dev --name "add-new-field"
shellscript
1# prisma migrate deploy > 마이그레이션 진행2prisma migrate deploy
2. Mongodb
2.1 NoSQL vs SQL
- SQL 데이터베이스는 미리 정의된 구조화된 Table과 Column, Row를 사용한다.
- NoSQL은 구조를 미리 정의할 필요가 없다.
- Document, Key-Value Pair 또는 Graph 형태로 모든 값을 원하는 형태로 저장 할 수 있다.
- NoSQL 데이터베이스의 종류
- Document → Mongodb
- Key Value → Redis
- Column → Cassandra
- Graph → Neo4J
- NoSQL을 사용해야하는 이유?
- NoSQL은 SQL에 비해 매우 유연하고 수평적 스케일링 (Horizontal Scaling)에 매우 유리하다.
- 대량의 데이터를 다루기위해 설계됐다.
- 지속적으로 구조가 변화는 데이터를 다룰 때 매우 유리하다
2.2 MongoDB
- MongoDB란?
- MongoDB는 Document 기반의 NoSQL 데이터베이스다.
- JSON과 유사한 구조 (BSON) 구조로 데이터를 저장한다.
- 스케일링이 쉽고 유연하고 사용성이 편리하다.
- MongoDB의 데이터 구조
- Document 형식으로 데이터를 저장한다. SQL에서의 Row와 같은 단위다.
- Collection에 비슷한 Document들을 보관한다. SQL에서의 Table과 같은 단위다
json
1{2"name": "John Doe",3"age": 30,4"email": "john@example.com",5"interests": ["hiking", "coding"]6}
2.3 기본 MongoDB CRUD 작업
데이터 생성 (Create)insertOne(): 한개의 Document를 생성insertMany(): 여러개의 Document를 생성
데이터 조회 (Read)find(): 여러개의 Document 조회findOne(): 한개의 Document 조회
데이터 업데이트 (Update)updateOne(): 한개의 Document 업데이트updateMany(): 여러개의 Document 업데이트
데이터 삭제 (Delete)deleteOne(): 한개의 Document 삭제deleteMany(): 여러개의 Document 삭제
2.4 Mongoose (ODM)
Prisma, TypeORM같은 Javascript SQL ORM이 존재하는 것처럼 MongoDB도 Mongoose라는 ODM이 존재한다.
기본기: 연결하기, CRUD, Populate고급기능: Middleware (Hook), VirtualPropertyRelationship: One to Many, Many to ManyTransaction
2.4.1 Mongoose (연결하기)
typescript
1const mongoose = require('mongoose')23async function connectDB() {4try {5await mongoose.connect('mongodb://localhost:27017/mydb')6console.log('MongoDB Connected')7} catch (err) {8console.error('Connection Error:', err)9}10}1112connectDB()
2.4.2 Mongoose (Schema 정의하기)
typescript
1const userSchema = new mongoose.Schema({2name: String,3age: Number,4email: String,5interests: [String],6})78const User = mongoose.model('User', userSchema)910const newUser = new User({11name: 'Code Factory',12age: 25,13email: 'admin@codefactory.ai',14interests: ['reading', 'music'],15})
2.4.3 Mongoose (Create 작업하기)
typescript
1async function createUser() {2try {3const user = await User.create({4name: '민지',5age: 21,6email: 'minji@codefactory.ai',7interests: ['dancing', 'singing'],8})9console.log('User created:', user)10} catch (err) {11console.error('Error creating user:', err)12}13}
2.4.4 Mongoose (Read 작업하기)
typescript
1async function findAllUsers() {2try {3const users = await User.find({})4console.log('User found:', users)5} catch (err) {6console.error('Error finding users:', err)7}8}
2.4.5 Mongoose (Update 작업하기)
typescript
1async function updateUser() {2try {3const updateUser = await User.updateOne(4{ email: '민지' }, //5{ $set: { age: 22 } },6)7console.log('User updated:', updateUser)8} catch (err) {9console.error('Error updating user:', err)10}11}
2.4.6 Mongoose (Delete 작업하기)
typescript
1async function deleteUser() {2try {3const deleteUser = await User.deleteOne({ name: '민지' })4console.log('User deleted:', deleteUser)5} catch (err) {6console.error('Error deleting user:', err)7}8}
2.4.7 Mongoose (Populate 유사 Join)
typescript
1const userSchema = new mongoose.Schema({2name: String,3age: Number,4email: String,5interests: [String],6})78const postSchema = new mongoose.Schema({9title: String,10author: {11type: mongoose.Schema.Types.ObjectId,12ref: 'User',13},14})1516async function findPostsWithAuthors() {17try {18const posts = await Post.find().populate('author').exec()19console.log('Posts & authors:', posts)20} catch (err) {21console.error('Error : ', err)22}23}
2.4.8 Mongoose (Middleware Hook)
typescript
1userSchema.pre('save', function (next) {2console.log('Saving user:', this.name)3next()4})56const User = mongoose.model('User', userSchema)
- pre → 이벤트 실행 전 / pos → 이벤트 실행 후
Document Middleware: save, validate, remove등 이벤트 실행시 실행Query Middleware:- updateOne, deleteOne, findOneAndUpdate등 특정 함수 실행시 실행 (Query Middleware)
2.5 Mongoose Relationships
2.5.1 One to One
typescript
1const mongoose = require('mongoose')23const profileSchema = new mongoose.Schema({4bio: String,5website: String,6location: String,7})89const userSchema = new mongoose.Schema({10name: String,11email: String,12profile: {13type: mongoose.Schema.Types.ObjectId,14ref: 'Profile',15},16})
typescript
1const userSchema = new mongoose.Schema({2name: String,3email: String,4profile: {5bio: String,6website: String,7location: String,8},9})
2.5.2 One to Many
typescript
1const commentSchema = new mongoose.Schema({2body: String,3date: Date,4postId: {5type: mongoose.Schema.Types.ObjectId,6ref: 'Post',7},8})910const postSchema = new mongoose.Schema({11title: String,12content: String,13comments: [14{15type: mongoose.Schema.Types.ObjectId,16ref: 'Comment',17},18],19})
2.5.3 Many to Many
typescript
1const roleSchema = new mongoose.Schema({2name: String,3users: [4{5type: mongoose.Schema.Types.ObjectId,6ref: 'User',7},8],9})1011const userSchema = new mongoose.Schema({12name: String,13roles: [14{15type: mongoose.Schema.Types.ObjectId,16ref: 'Role',17},18],19})
2.5.4 Mongoose (Transaction)
typescript
1const session = await mongoose.startSession()2session.startTransaction()34try {5const user = new User({ name: '민지', email: 'minji@codefactory.ai' })6await user.save({ session })78const post = new Post({ title: "Minji's Post", author: user._id })9await post.save({ session })1011await session.commitTransaction() // 커밋12session.endSession() // 세션 종료13} catch (error) {14await session.abortTransaction() // 롤백15session.endSession()16throw error17}