본문 바로가기

Nodejs

[Node.js] 프로젝트 생성 및 mongoDB 연결하기

프로젝트 생성 및 설정

1. 프로젝트 시작하기 (내 프로젝트 package화)

npm init
더보기

( * 괄호 안에 값이 있으면 엔터를 쳤을 때 자동으로 설정됩니다. * ) 

name : 프로젝트 이름
version : 버전
description : 설명 (직접 쓰기를 권장)
entry point: 어떤 js파일이 package를 구동시키는 첫 시작인지
test command : TDD(Test Driven Development : 테스트 주도 개발)를 할 때 test를 실행시킬 명령어
git repository : git repo 주소

 

1-1. 이미 client가 있다면 server 폴더를 만들고 cd server

 

 

2.  express와 nodemon, mongoose 설치 

npm install express nodemon mongoose body-parser
더보기

express : node js 프레임워크

nodemon : 코드 변경시 서버 자동으로 다시 실행

mongoose : mongoDB 

body-parser : req body요청을 구문 분석하고 올바른 방법으로 돌려줌

 

3. package.json 수정

//package.json
"scripts": {
	"test" : "~~" =>    "start" : "nodemon app.js"
}

 

4.  환경 조성

//app.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");


app.use(bodyParser.json());

app.listen(3000);

 

MongoDB 만들기 

1. node 설치 확인

node -v

설치 안 되어있으면 설치하기 -> https://nodejs.org/ko/

 

2. .env 설치

사용자 이름과 비밀번호를 숨기기 위해 .env사용

npm install dotenv

 

3. DB 만들기

  1. https://www.mongodb.com/ 회원가입
  2. 새로운 프로젝트 생성
  3. 새로운 DB 생성
  4. Cloud Provider & Region : AWS, Singapore 선택, Cluster Tier : M0 꼭! Cluster Name : 원하는 DB명
  5. 5분 정도 후 생성완료
  6. connect 버튼 클릭 후 connect your application 선택
  7. node.js, 3.0 or later 선택
  8. 아래 connection String Only 주소 복사
    더보기
    mongodb+srv://govl6113:<password>@youtube-clone.km5tc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
  9. Database Access 들어가서 ADD NEW USER 버튼 누르기
  10. user name과 password 입력 후 ADD USER 버튼눌러서 완료 
  11. 10에서 만든 user name과 password를 8번 주소 알맞은 자리에 넣기

 

MongoDB 연결하기

  1.  .env파일만들기 (package.json과 같은 위치에) 
  2. //.env
    DB_CONNECTION= {8번 주소}
     
  3. //app.js
    require('dotenv/config');
    
    
    //Connect To DB
    mongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser: true}, () => 
        console.log('connected to DB')
    );

 

프로젝트 실행

npm start