Skip to Content
BackendNestJs46-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
1
datasource db {
2
provider = "postgresql"
3
url = "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
1
generator client {
2
provider = 'prisma-client-js'
3
output = './generated/prisma-client-js'
4
}
  • provider는 제너레이터 툴을 정의한다.
  • output은 API 파일을 생성할 위치를 정의한다

1.1.3 Model

typescript
1
model Comment {
2
id Int @id @default(autoincrement())
3
title String
4
content String
5
}
6
7
model Tag {
8
name String @id
9
}
  • Model은 테이블 정보를 정의한다.
  • Scalar, Relation, Type Modifier 등을 사용해서 테이블을 정의할 수 있다

1.1.4 Enum

typescript
1
model User {
2
id Int @id @default(autoincrement())
3
email String @unique
4
name String?
5
role Role @default(USER)
6
}
7
8
enum Role {
9
USER
10
ADMIN
11
}
  • TypeORM에서 다뤘던 enum 개념과 같다고 생각하면 된다.
  • 특정 값만 입력되도록 유도 할 수 있다

1.1.5 Relations

typescript
1
model User {
2
id Int @id @default(autoincrement())
3
name String
4
posts Post[]
5
}
6
7
model Post {
8
id Int @id @default(autoincrement())
9
title String
10
userId Int
11
user 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 타입
StringText
BooleanBoolean
IntInteger
BigIntBigInt
FloatReal/Double Precision
DecimalNumeric
DateTimeTimestamp/ Timestamptz
JsonJSON/JSONB
BytesBYTEA

1.3 Attributes

속성설명
@idPrimary Key
@default기본값
@unique유니크/유일무이 값
@relation모델 간 관계
@map테이블의 다른 칼럼으로 매핑
@updatedAt업데이트 순간 DateTime 기록
@@idComposite Primary Key
@@uniqueComposite Unique Key
@@indexIndex Keys

1.4 Prisma Client

typescript
1
genreator client {
2
provider = 'prisma-client-js'
3
}
shellscript
1
$ npm install @prisma/client
2
$ prisma generate
  • generator에 prisma client 정의
  • @prisma/client 설치
  • prisma generate 실행 (@prisma/client 설치시 자동 실행)

1.4.1 Prisma Client 작업 플로우

nestjs-fastcam_46-1


1.4.2 Prisma Client 작동 방식

nestjs-fastcam_46-2


1.4.3 Prisma Create

typescript
1
const user = await prisma.user.create({
2
data: {
3
email: 'admin@codefactory.ai',
4
name: 'Code Factory',
5
},
6
})
typescript
1
const createMany = await prisma.user.createMany({
2
data: [
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
],
8
skipDuplicates: true, // 원영 스킵됨
9
})

1.4.4 Prisma Read (1)

typescript
1
const user = await prisma.user.findUniquye({
2
where: { email: 'minji@codefactory.ai' },
3
})
typescript
1
const result = await prisma.user.findFirst({
2
where: {
3
email: { endsWith: 'codefactory.ai' },
4
},
5
})

1.4.5 Prisma Read (2)

typescript
1
const user = await prisma.user.findMany({
2
where: {
3
email: { endsWith: 'codefactory.ai' },
4
},
5
})
typescript
1
const users = await prisma.user.findMany({
2
where: {
3
OR: [
4
{ name: { startsWith: 'E' } },
5
{
6
AND: {
7
profileViews: { gt: 0 },
8
role: { 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
1
const getUser = await prisma.user.findUnique({
2
where: { id: 22 },
3
select: {
4
email: true,
5
name: true,
6
},
7
})

email과 name 칼럼만 선택


1.5.2 Prisma Read Relation 포함하기

typescript
1
const users = await prisma.user.findMany({
2
include: {
3
posts: {
4
select: { title: true },
5
},
6
},
7
})

user 값에 post 관계 포함해서 반환


1.5.3 Relation Filtering Some

typescript
1
const result = await prisma.user.findMany({
2
where: {
3
post: {
4
some: {
5
content: { contains: 'Code Factory' },
6
},
7
},
8
},
9
})

Code Factory를 content에 포함하고 있는 post가 존재하는 user를 모두 가져옴


1.5.4 Relation Filtering Every

typescript
1
const result = await prisma.user.findMany({
2
where: {
3
post: {
4
every: { published: true },
5
},
6
},
7
})

관련된 post의 published가 모두 true인 user를 모두 가져옴


1.5.5 Relation Filtering None

typescript
1
const result = await prisma.user.findMany({
2
where: {
3
post: {
4
none: { published: true },
5
},
6
},
7
})

관련된 post의 published가 모두 true가 아닌 User를 모두 가져옴


1.5.6 Relation Filtering Is

typescript
1
const result = await prisma.user.findMany({
2
where: {
3
user: {
4
is: { name: 'Code Factory' },
5
},
6
},
7
})

name 필드가 Code Factory인 post를 모두 가져옴


1.5.7 Relation Filtering IsNot

typescript
1
const result = await prisma.user.findMany({
2
where: {
3
user: {
4
isNot: { name: 'Code Factory' },
5
},
6
},
7
})

name 필드가 Code Factory가 아닌 User를 모두 가져옴


1.5.8 Update

typescript
1
const updateUser = await prisma.user.update({
2
where: { email: 'test@codefactory.ai' },
3
data: { name: '민지' },
4
})

사용자의 name 필드를 ‘민지’로 변경


1.5.9 Delete

typescript
1
const deleteUser = await prisma.user.delete({
2
where: { email: 'test@codefactory.ai' },
3
})

email이 test@codefactory.ai인 사용자를 삭제


1.5.10 Relationship One to One

typescript
1
model User {
2
id Int @id @default(autoincrement())
3
profile Profile @relation(fields: [profileId], references: [id])
4
profileId Int @unique // 필수 (1:1이니까ㅣ 당연히)
5
}
6
7
model Profile {
8
id Int @id @default(autoincrement())
9
user User? // nullable만 가능
10
}
typescript
1
model User {
2
id Int @id @default(autoincrement())
3
profile Profile? @relation(fields: [profileId], references: [id])
4
profileId Int? @unique // Optional 생성 가능
5
}
6
7
model Profile {
8
id Int @id @default(autoincrement())
9
user User?
10
}

1.5.11 Relationship One to Many

typescript
1
model User {
2
id Int @id @default(autoincrement())
3
posts Post[]
4
}
5
6
model Post {
7
id Int @id @default(autoincrement())
8
author User @relation(fields: [authorId], references: [id])
9
authorId Int
10
}

1.5.12 Relationship Many to Many

typescript
1
model Post {
2
id Int @id @default(autoincrement())
3
title String
4
categories CategoriesOnPosts[]
5
}
6
7
model Category {
8
id Int @id @default(autoincrement())
9
name String
10
posts CategoriesOnPosts[]
11
}
12
13
model CategoriesOnPosts {
14
post Post @relation(fields: [postId], references: [id])
15
postId Int
16
category Category @relation(fields: [categoryId], references: [id])
17
categoryId Int
18
assignedAt DateTime @default(now())
19
assignedBy String
20
@@id([postId, categoryId])
21
}
typescript
1
model Post {
2
id Int @id @default(autoincrement())
3
title String
4
categories Category[]
5
}
6
7
model Category {
8
id Int @id @default(autoincrement())
9
name String
10
posts Post[]
11
}

1.6 Aggregate Function

함수설명
_avg평균
_count개수
_sum합계
_min최소 값
_max최대 값

1.6.1 Aggregate

typescript
1
const aggregations = await prisma.user.aggregate({
2
_avg: { age: true },
3
})

1.6.2 Raw Query

typescript
1
const result = await prisma.$queryRaw('SELECT * FROM User')

1.6.3 Migration

shellscript
1
# prisma migrate dev > 마이그레이션 파일 생성 (자동)
2
prisma migrate dev --name "add-new-field"
shellscript
1
# prisma migrate deploy > 마이그레이션 진행
2
prisma 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), VirtualProperty
  • Relationship : One to Many, Many to Many
  • Transaction

2.4.1 Mongoose (연결하기)

typescript
1
const mongoose = require('mongoose')
2
3
async function connectDB() {
4
try {
5
await mongoose.connect('mongodb://localhost:27017/mydb')
6
console.log('MongoDB Connected')
7
} catch (err) {
8
console.error('Connection Error:', err)
9
}
10
}
11
12
connectDB()

2.4.2 Mongoose (Schema 정의하기)

typescript
1
const userSchema = new mongoose.Schema({
2
name: String,
3
age: Number,
4
email: String,
5
interests: [String],
6
})
7
8
const User = mongoose.model('User', userSchema)
9
10
const newUser = new User({
11
name: 'Code Factory',
12
age: 25,
13
email: 'admin@codefactory.ai',
14
interests: ['reading', 'music'],
15
})

2.4.3 Mongoose (Create 작업하기)

typescript
1
async function createUser() {
2
try {
3
const user = await User.create({
4
name: '민지',
5
age: 21,
6
email: 'minji@codefactory.ai',
7
interests: ['dancing', 'singing'],
8
})
9
console.log('User created:', user)
10
} catch (err) {
11
console.error('Error creating user:', err)
12
}
13
}

2.4.4 Mongoose (Read 작업하기)

typescript
1
async function findAllUsers() {
2
try {
3
const users = await User.find({})
4
console.log('User found:', users)
5
} catch (err) {
6
console.error('Error finding users:', err)
7
}
8
}

2.4.5 Mongoose (Update 작업하기)

typescript
1
async function updateUser() {
2
try {
3
const updateUser = await User.updateOne(
4
{ email: '민지' }, //
5
{ $set: { age: 22 } },
6
)
7
console.log('User updated:', updateUser)
8
} catch (err) {
9
console.error('Error updating user:', err)
10
}
11
}

2.4.6 Mongoose (Delete 작업하기)

typescript
1
async function deleteUser() {
2
try {
3
const deleteUser = await User.deleteOne({ name: '민지' })
4
console.log('User deleted:', deleteUser)
5
} catch (err) {
6
console.error('Error deleting user:', err)
7
}
8
}

2.4.7 Mongoose (Populate 유사 Join)

typescript
1
const userSchema = new mongoose.Schema({
2
name: String,
3
age: Number,
4
email: String,
5
interests: [String],
6
})
7
8
const postSchema = new mongoose.Schema({
9
title: String,
10
author: {
11
type: mongoose.Schema.Types.ObjectId,
12
ref: 'User',
13
},
14
})
15
16
async function findPostsWithAuthors() {
17
try {
18
const posts = await Post.find().populate('author').exec()
19
console.log('Posts & authors:', posts)
20
} catch (err) {
21
console.error('Error : ', err)
22
}
23
}

2.4.8 Mongoose (Middleware Hook)

typescript
1
userSchema.pre('save', function (next) {
2
console.log('Saving user:', this.name)
3
next()
4
})
5
6
const 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
1
const mongoose = require('mongoose')
2
3
const profileSchema = new mongoose.Schema({
4
bio: String,
5
website: String,
6
location: String,
7
})
8
9
const userSchema = new mongoose.Schema({
10
name: String,
11
email: String,
12
profile: {
13
type: mongoose.Schema.Types.ObjectId,
14
ref: 'Profile',
15
},
16
})
typescript
1
const userSchema = new mongoose.Schema({
2
name: String,
3
email: String,
4
profile: {
5
bio: String,
6
website: String,
7
location: String,
8
},
9
})

2.5.2 One to Many

typescript
1
const commentSchema = new mongoose.Schema({
2
body: String,
3
date: Date,
4
postId: {
5
type: mongoose.Schema.Types.ObjectId,
6
ref: 'Post',
7
},
8
})
9
10
const postSchema = new mongoose.Schema({
11
title: String,
12
content: String,
13
comments: [
14
{
15
type: mongoose.Schema.Types.ObjectId,
16
ref: 'Comment',
17
},
18
],
19
})

2.5.3 Many to Many

typescript
1
const roleSchema = new mongoose.Schema({
2
name: String,
3
users: [
4
{
5
type: mongoose.Schema.Types.ObjectId,
6
ref: 'User',
7
},
8
],
9
})
10
11
const userSchema = new mongoose.Schema({
12
name: String,
13
roles: [
14
{
15
type: mongoose.Schema.Types.ObjectId,
16
ref: 'Role',
17
},
18
],
19
})

2.5.4 Mongoose (Transaction)

typescript
1
const session = await mongoose.startSession()
2
session.startTransaction()
3
4
try {
5
const user = new User({ name: '민지', email: 'minji@codefactory.ai' })
6
await user.save({ session })
7
8
const post = new Post({ title: "Minji's Post", author: user._id })
9
await post.save({ session })
10
11
await session.commitTransaction() // 커밋
12
session.endSession() // 세션 종료
13
} catch (error) {
14
await session.abortTransaction() // 롤백
15
session.endSession()
16
throw error
17
}