playground_avec coding

[Node.js] Mongo DB 연결하기 본문

front-end/node.js

[Node.js] Mongo DB 연결하기

Nat 2021. 5. 31. 22:18


저번에 작성한 boiler-plate 라는 폴더에  mongo DB 연결 하는 방법

https://www.mongodb.com/ 

 

The most popular database for modern apps

We're the creators of MongoDB, the most popular database for modern apps, and MongoDB Atlas, the global cloud database on AWS, Azure, and GCP. Easily organize, use, and enrich data — in real time, anywhere.

www.mongodb.com

1. 회원가입
2. cluster(클러스터) 생성
- cluster 생성

- 1. IP address 만들어라
- 2. Database User 의 ID 와 PW 를 만들어라 
- 3. choose a connection method
- 4. Connect your application
- 5. Add your connection string into your application code 
copy 하고 pw 를 쳐준다. 

3. Mongo DB 유저 생성. 
4. Mongoose 설치. 
Node.js 를 설치하였으면 vscode 터미널 창에서 
npm install mongoose --save 명령어를 친 후 로딩 다 된후에
package.json 에 dependencies 에 
"mongoose": "^5.12.11" 가 뜬 것을 확인 할 수 있다. 
Mongo DB 를 편하게 쓸 수 있는 object Modeling Tool 이다

https://www.npmjs.com/package/mongoose 를 참조하여 작성해줬다. 

 


app 에 MongoDB 연결

index.js 에서 

const mongoose = require ('mongoose')
mongoose.connect('mongodb+srv://나의Database user명:password@cluster0.bnqwd.mongodb.net/myFirstDatabase?retryWrites=true&w=majority\
',{
    useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false
}).then(() => console.log('MongoDB connected...'))
.catch(err =>console.log(err))

 

 

연결되면 'MongoDB connected...' 으로 터미널 창에서 나오게 자바스크립트(ES6) 코드를 쳐 준다.

그 외 오류방지를 위해 useNewUrlParser, useUnifiedTopology,useCreateIndex,useFindAndModify 라고 설정해준다.

.catch( err => console.log(err) ) 에러가 뜨면 catch 구문으로 err 이라고 뜨게 쳐준다. 

 

mongoose를 통해 연결된 database 정보를 mongoose.connect('MongoDB 정보') 를 쳐준다.