티스토리 뷰

React와 NextJS

MongoDB with NextJS

skim88 2024. 11. 11. 09:00
반응형

MongoDB with NextJS
MongoDB with NextJS

이직 준비 중 개발자로서의 나의 실력을 보여줄 길이 토이프로젝트 밖에 없다는 것을 알게 된 후 작은 토이프로젝트를 만들어서 실무에서 해보지 못했던 것들을 만들어보고 있다.

그 중 ‘NextJS 에서 API 구성하기’와 ‘MongoDB 사용해보기’를 시도해보았고 생각보다 간단하여 정리해보려 한다.(NextJS 프로젝트 생성은 skip한다)


1. mongodb 가입 및 db 생성

MongoDB 공식 페이지
MongoDB 공식 페이지

2. 무료 DB Deploy

무료 배포 선택
무료 배포 선택

3. db username과 password 생성

db username과 password 생성
db username과 password 생성

4. IP 설정

(기본 IP 설정을 그대로 두고 이후 NextJS 배포 후 추가 셋팅 필요)

IP 설정
IP 설정

5. 테스트를 위해 sample data load

테스트를 위해 sample data load
테스트를 위해 sample data load

6. mongodb package install

npm install mongodb

7. ./lib/mogodb.ts 생성

(DB_CONNECT_URI 환경변수 셋팅 SKIP)

import { MongoClient, Db } from 'mongodb'
import Exception, { CF_ERROR_CODES } from '@/configs/error'

const connectToDatabase = async () => {
  const uri: string | undefined = process.env.DB_CONNECT_URI
  if (!uri) {
    throw new Exception(CF_ERROR_CODES.ENV_UNDEFINED)
  }
  try {
    if (uri === undefined) throw new Exception(CF_ERROR_CODES.ENV_UNDEFINED)
    const mongoClient: MongoClient | null = await newMongoClient(uri).connect()
    const database: Db | null = mongoClient.db('Test')
    return { mongoClient, database }
  } catch (e) {
    console.error(e)
  }
}

export default connectToDatabase

(Exception과 Error는 없어도 상관없음)

8. ./pages/test_list.ts 생성

import { NextApiRequest, NextApiResponse } from 'next/types'
import { Db } from 'mongodb'
import { connectToDatabase } from '@/lib/mongodb'
import Exception, { CF_ERROR_CODES } from '@/configs/error'

const handler = async (request: NextApiRequest, response: NextApiResponse) => {
  const connection = await connectToDatabase()
  const database: Db | undefined = connection?.database
  
  if (database === undefined) throw new Exception(CF_ERROR_CODES.DB_CONNECTION_UNDFINED)
  
  const collection = database.collection('Test1')
  
  if (request.method === 'GET') {
    const results = await collection.find({}).limit(10).toArray()
    response.status(200).json(results)
  } else if (request.method === 'POST') {
  const condition: string | string[] | undefined = request.query.id
  if (condition === undefined) throw new Exception(CF_ERROR_CODES.NO_QUERY_PARAMS)
  
  const data = request.body
  //...
  }
}

export default handler

9. API 호출

const [test, setTest] = useState()

useEffect(() => {
  const fetchData = async () => {
  const results = await fetch('/api/test_list').then((response) => response.json())
  setTest(results)
}
  fetchData()
}, [])

DB연결이 정말 간편하다고 느꼈지만, MongoDB 자체가 익숙하지 않아 더 사용해보면서 사용법을 익혀야 할 것 같다.

 

반응형
Total
Today
Yesterday
반응형