본문 바로가기
  • 삽질하는 자의 블로그
Node.js(Express)

9. DB 연결 ( mongoDB ), 환경변수의 사용 Feat. POSTMAN,dotenv

by 이게뭐당가 2023. 2. 18.

이제 실제로 DB 를 연결해보도록하자.

 

우선 DB 에 연결하기 전에, DB에 연결하는 API Key 를 숨기기 위하여, .env 에 설정하여 코드를 숨기도록 하자.

 

1. env 설정

2. database 를 연결할 함수,  실제로 데이터교환을 할 함수를 생성한다.

 

dotenv 를 통해, 환경변수를 사용하여 URL 을 가져오고, 해당 URL 로 연결한다.

< database / database.js >

    const { MongoClient } = require("mongodb");
    require("dotenv").config();		// dotenv 를 사용할 수 있도록 require 한다.

    const url = process.env.MONGODB_URL;		// 환경변수에서 온 URL
    let database;

    const connectDb = async () => {		// 앱에 연결할 함수
      const client = await MongoClient.connect(url);
      database = client.db("feeling-diary");	// 데이터베이스 이름을 통해 연결
    };

    const getDb = () => {		// 데이터베이스에 접근할 함수
      if (!database) {
        throw new Error("연결이 실패했습니다.");
      }
      return database;
    };

    module.exports = {		// exports 한다.
      connectDb,
      getDb,
    };

 

3. index.js 에서, 서버에 DB 를 연결한다.

 

const express = require("express");
const { connectDb } = require("./database/database");	// 연결할 함수를 불러오고

const app = express();
	...

connectDb()			// 서버에 데이터베이스를 연결한다.
  .then(() => {
    app.listen(5000);
  })
  .catch((error) => {		// 오류발생시 나올 console
    console.log(error);
  });

 

 

4. 컨트롤러에 가서, DB 에 접근하는 로직( GET, POST) 을 추가한다.

 

const { diaryValidation } = require("../helper/diary-valdation");
const { getDb } = require("../database/database");		// DB 에 접근할 함수 import

const getUserDiary = async (req, res, next) => {	// user 데이터를 가져오는 로직
		...
  const response = await getDb()			// mongodb 쿼리를 통해 가져올 수 있다.
    .collection("diary")
    .find({ userEmail })
    .toArray();

  res.json({ message: "this is diary", data: response });	// 응답한다.
};

const postUserDiary = async (req, res, next) => {	// user 데이터를 보내는 로직
  const errorCheck = diaryValidation(req.body);

  if (errorCheck !== null) {
    next(errorCheck);
    return;
  }
  const { userEmail, diaryTitle, diaryContent, feeling, date } = req.body;	// body값을 받아

  const inputData = {
    userEmail,
    diaryTitle,
    diaryContent,
    feeling,
    date,
  };

  const response = await getDb().collection("diary").insertOne(inputData);	// DB 에 넣는다.

  res.status(201).json({ message: "success", data: response });	// 결과를 응답한다.
};

module.exports = {
  getUserDiary,
  postUserDiary,
};

 

5. POSTMAN 을 통해, API 요청을 넣어 확인해보자.

 

POSTMAN 은 API 요청을 대신 해주는 애플리케이션이다.

GET 요청은 주소창에 치는 것으로 확인 할 수 있지만, POST 요청은 결과값을 확인하기 위해 요청을 보내야 하므로,

POSTMAN 을 이용해보자.

 

좋다 Validation 로직도 잘 실행되고, 결과값도 잘 들어간다.

 

댓글