성장과정(dev)/Frontend(feat. Vue, Next.js)

[node js] mongoDB 연결하기

lowellSunny 2020. 10. 23. 16:53

1. mongoDB 계정생성 및 로그인

 

2. mongoDB 클러스터 생성( Create a new cluster )

- 무료티어가 있는 나라 중 가장 가까운 나라 싱가포르로 선택(서울은 무료제공이 없음)

- 클러스터를 몇번 이상 생성하면 더이상 만들어지지 않음

- 생성하는데에 5~7분정도 소요

 

3. node  module에 mongoose 설치

- 몽고디비를 쉽게 연결할 수 있도록 도와주는 툴

- 명령어 : npm install mongoose --save

 

4. DB 연결정보 가져오기 및 연결

- connect 클릭

connect your application에서 db정보 복사

- 최상위의 index.js에서 복사한 주소 mongoose를 이용해 mongoDB 연결

const mongoose = require( 'mongoose' )

//  에러방지 옵션설정
mongoose.connect( 'mongodb+srv://lowell:<password>@boilerplate.u5mg9.mongodb.net/<dbname>?retryWrites=true&w=majority', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: true
} ) .then(() => console.log( "MongoDB Connected success !!" ))
    .catch(err => console.log( err ))

 

- 여기서 나는 db접근권한 에러가 발생하였다.

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: http
s://docs.atlas.mongodb.com/security-whitelist/

 

- 이 때는 mongo DB 에서 해당 클러스터에 ip를 허용해줘야함

(ADD CURRENT IP ADDRESS 클릭 시 나의 현재 LOCAL IP를 허용해줌)

연결성공 !