몽고DB란?

 

몽고 DB 는 위키백과에 다음과 같이 설명되어 있다.

몽고DB(MongoDB←HUMONGOUS)는 크로스 플랫폼 도큐먼트 지향 데이터베이스 시스템이다. NoSQL 데이터베이스로 분류되는 몽고DB는 JSON과 같은 동적 스키마형 도큐먼트들(몽고DB는 이러한 포맷을 BSON이라 부름)을 선호함에 따라 전통적인 테이블 기반 관계형 데이터베이스 구조의 사용을 삼간다. 이로써 특정한 종류의 애플리케이션을 더 쉽고 더 빠르게 데이터 통합을 가능케 한다. 아페로 GPL 아파치 라이선스를 결합하여 공개된 몽고DB는 자유-오픈 소스 소프트웨어이다.

이러한 몽고DB를 node.js에서 사용하기 위해서는 moongoose라는 ODM을 사용해야 한다. ODM은 Object Cocument Mapping으로 문서를 DB에서 조회할 때 자바스크립트 객체로 바꿔주는 역할을 한다. 

 

mongo DB와 이전에 Express.js로 제작한 간단한 웹 애플리케이션과 연결하는 과정은 다음과 같다.

 

1. 몽고 DB 회원가입

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

Try Free를 눌러 회원가입

 

2. Cluster 생성

Free인 M0 Sandbox tier를 선택

 

 

3. 몽고 DB 유저 생성

CONNECT를 눌러 몽고DB 유저 생성 

4. MongGoose 다운로드

 

npm install mongoose --save

5. index.js 파일 추가

 

CONNECT -> URL COPY

-> index.js

const express = require('express')
const app = express()
const port = 5000
const mongoose = require('mongoose')
mongoose.connect('MongoDB URL',{
	useNewUrlParser: true, 
    useUnifiedTopology: true,
    useCreateIndex: true, 
    useFindAndModify:false
}).then(() => console.log('MongoDB Connected...')).catch(err => console.log(err))
app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

- 코드 설명

'mongodb+srv://<username>:<password>@boilerplate.16rla.mongodb.net/<dbname>?retryWrites=true&w=majority'

 

<username> : 이전에 생성한 몽고DB 유저 ID

<password> : 이전에 생성한 몽고DB 유저 비밀번호

<mongodb> : 생성한 몽고DB 이름

 

*.then(()=>console.log('MongoDB Connected...')) : 연결확인 여부를 위한 console에 띄우는 로그

 

* .catch(err => conseole.log(err)) : 연결이 되지 않은 경우에는 errlog로 띄움

 

* 에러방지를 위한 코드

useNewUrlParser: true,

useUnifiedTopology: true,

useCreateIndex: true,

useFindAndModify: false

 

 

6. 실행

 

npm run start

 

 

+ Recent posts