본문 바로가기

Backend/Node.js

Node.js (Express) mongoose 연동

NodeJS에서 mongoose 모듈을 활용하여 mongodb를 연동해볼게요.

아주 간단해요.

이 글은 몽고DB를 연결하는 데에 목적이 있어요. (사실 연결할 때마다 구글에 검색해서 긁어오기 귀찮아서..)

mongoose 모듈을 활용하여 crud하는 기능은 차후에 별도로 포스팅할 예정이에요~!

 

mongoose 설치

npm install mongoose

mongodb.js 설정

혹시 비밀번호가 있다면 mongodb://username:password@localhost:27017/demo

 

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/demo', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
})

const connection = mongoose.connection
connection.on('error', console.error)
connection.once('open', () => {
  console.log('Connected to mongod server')
})

app.js에 추가

여기까지 하시고 서버를 켰을 때 Connected to mongod server가 콘솔에 찍히면 연결이 잘 된거에요!

사실 이 글의 목적은 여기까지입니다... 지나칠 정도로 쉽죠.

전 원래 자바 개발자인데 노드+몽고의 간결함과 유연함에 매력을 느끼게 된 이후로 개인 프로젝트는 모두 노드+몽고로 하게 됬어요.

 

require('./src/datas/mongodb')

Boards.js - Schema 생성

그래도 좀 시시하니 한 번 몽고디비에 collection을 만들고 document를 입력하고 조회까지 해볼게요.

 

const mongoose = require('mongoose')

const Schema = mongoose.Schema
const ObjectId = Schema.ObjectId

module.exports = mongoose.model('Boards', new Schema({
  title: { type: String },
  content: { type: String },
  likeCount: { type: Number, default: 0 },
  createdAt: { type: Date, default: Date.now },
}, {
  versionKey: false
}))

routes/boards.js

대충 아래와 같이 기본 코딩하시면 되요.

 

const express = require('express')
const router = express.Router()

const Boards = require('../datas/model/Boards')

router.get('/', (req, res, next) => {
  Boards.find((err, board) => {
    res.json(board)
  })
})

router.post('/', (req, res, next) => {
  const { title, content } = req.body
  const boards = new Boards({
    title: title,
    content: content
  })
  boards.save((err, board) => {
    res.json(board)
  })
})

module.exports = router

테스트

게시글 등록 몇개 해주고 조회하면!

 

### 게시글 리스트 조회
GET http://localhost:8080/boards

### 게시글 등록
POST http://localhost:8080/boards
Content-Type: application/json

{
  "title": "제목임",
  "content": "내용임"
}

응답

이런 응답을 받을 수 있어요.

위에서 스키마 생성할 때 versionKey를 false로 주면 도큐먼트를 생성할 때 __v가 생기지 않아요.

 

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 407
ETag: W/"197-PNv5SAcboCSn/SC4BKFowwcXTVE"
Date: Fri, 04 Dec 2020 17:05:35 GMT
Connection: close

[
  {
    "likeCount": 0,
    "_id": "5fca6b88864d6610a1cb56af",
    "title": "제목임",
    "content": "내용임",
    "createdAt": "2020-12-04T17:02:00.392Z",
    "__v": 0
  },
  {
    "likeCount": 0,
    "_id": "5fca6b9f864d6610a1cb56b0",
    "title": "제목임",
    "content": "내용임",
    "createdAt": "2020-12-04T17:02:23.376Z",
    "__v": 0
  },
  {
    "likeCount": 0,
    "_id": "5fca6c229c8c13112588ea72",
    "title": "제목임",
    "content": "내용임",
    "createdAt": "2020-12-04T17:04:34.783Z"
  }
]