본문 바로가기

Study/Next

mongoDB

next.js with MongoDB

  1. mongo DB 웹사이트에서 클러스터를 생성한다. 이 때 클러스트는 DB를 호스팅할 서버를 말한다.
  2. mongodb를 사용하기 위해 프로젝트에 mongodb 패키지를 설치한다(문서).

 

yarn add mongodb 
# or
npm install mongodb

 

  1. 설치된 mongodb 라이브러리를 통해 서버 측에서 동작하는 코드로 클러스터에 접근, 데이터를 저장하고 불러올 수 있다.
  2. 다시 웹사이트로 돌아가서, 처음 단계에서 생성한 클러스터의 connect 버튼을 클릭하면, 프로젝트와 클러스터를 연결할 방법을 선택할 수 있다.
    • 화면에 체크된 옵션을 선택하면 connetion url을 확인할 수 있다.
     

 

  1. Security/Network Access 탭에서 DB에 접근 가능한 IP 목록(white list)을 추가한다.
    • 개발을 진행 중인 로컬 머신의 IP
    • 어플리케이션 배포 서버의 IP
  2. 서버 측 코드에 다음과 같이 작성하면, 클러스터에 접근할 수 있게 된다.
    import { MongoClient } from 'mongodb'
    
    const client = new MongoClient(process.env.url); // environmental var
    
    async function addUser(userName) {
      // Use connect method to connect to the server
      await client.connect();
      console.log('Connected successfully to server');
    
    	// now you can access to the db
      const db = client.db(dbName);
      const collection = db.collection('documents');
    
      // do something...
      await collection.insertOne({userName})
      client.close()
    }
    
    addUser("hyeonju")
      .then(console.log)
      .catch(console.error)
      .finally(() => client.close());
    
  3. db > collection > document의 관계를 갖는다. 이 때 document는 js 객체 데이터가 된다.

error handling

  1. db와 관련된 로직이 항상 바르게 동작하는 것은 아니다.
  2. (희박하긴 하지만) db와 제대로 연결이 되지 않는 경우, document이 제대로 삽입되지 않는 경우가 있을 수 있다.

 

    try {
      client = await connectDB()
    } catch (error) {
      res.status(500).json({ message: 'connecting database failed', error })
      return
    }

    try {
      await insertEmail(client, userEmail)
    } catch (error) {
      res.status(500).json({ message: 'inserting email failed', error })
      return
    }

 

'Study > Next' 카테고리의 다른 글

API route  (0) 2022.10.20
what is _document.js?  (1) 2022.10.18
optimization with <head> & <image>  (1) 2022.10.18
client side data fetching  (0) 2022.10.17
pre-rendering  (0) 2022.10.14