본문 바로가기
Web/Node.js

Node.js와 mongoose로 간단한 게시판 만들기

by supdev 2017. 7. 11.

* 전체 소스는 아래 github에 등록되어 있습니다.

https://github.com/Yun-hyunyoung/Nodejs-board-sample


node.js에서 mongodb로 데이터 입력 및 ejs로의 데이터 전송을 연습하기 위해

간단한 게시판 Sample을 만들어보려고 합니다.

mongodb가 설치되어 있어야 하며 기준 database의 이름mydb로 설정되어 있습니다.


먼저 mongoose를 설치하고 app.js에 mongodb와 연결하는 코드를 입력합니다.

npm install mongoose


app.js

...
// mongodb setup
var mongoose = require('mongoose');
var promise = mongoose.connect('mongodb://localhost/mydb', {
    useMongoClient: true
});

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    // we're connected!
    console.log('connected successfully');
});
...


Board model과 Comment model을 작성합니다.

boardSchema의 comments 컬럼에는 commentSchema를 배열 형태로 넣어줍니다.


models/board.js

var mongoose = require('mongoose'); var Schema = mongoose.Schema; var commentSchema = new Schema({     contents: String,     author: String,     comment_date: {type: Date, default: Date.now()} )}; var boardSchema = new Schema({     title: String,     contents: String,     author: String,     board_date: {type: Date, default: Date.now()},     comments: [commentSchema] }); module.exports = mongoose.model('board', boardSchema);


models/comment.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var commentSchema = new Schema({
    contents: String,
    author: String,
    comment_date: {type: Date, default: Date.now()}
)};

module.exports = mongoose.model('comment', commentSchema);


라우팅 파일을 작성합니다.

기능은 5가지로 구성되어 있습니다.


1. Root 페이지로 이동 : GET : /

root 페이지로 이동하며 db에 board collections을 쿼리하여 그 데이터를 ejs로 넘겨줍니다.


2. 글쓰기 페이지로 이동 : GET : /write

글쓰기 페이지로 이동


3. 글쓰기 : POST : /board/write

form 데이터를 가져와 mongodb board collection에 입력


4. 글 찾기 : GET : /board/:id

board의 id값으로 글을 찾아 데이터를 ejs로 넘겨줍니다.


5. 댓글 입력 : POST : /comment/write

form 데이터를 가져와 mongodb board collections에 comments document로 $push 합니다.

실제 입력된 데이터

> db.boards.find().pretty();
{
        "_id" : ObjectId("5964c257dcc0900b20c630a1"),
        "author" : "길동",
        "contents" : "내용",
        "title" : "제목",
        "comments" : [
                {
                        "author" : "관순",
                        "contents" : "댓글",
                        "_id" : ObjectId("5965994d78a21010206b65ba"),
                        "comment_date" : ISODate("2017-07-12T03:34:46.385Z")
                },
                {
                        "author" : "관순이",
                        "contents" : "댓글2",
                        "_id" : ObjectId("596599c7f9d7811200462142"),
                        "comment_date" : ISODate("2017-07-12T03:37:28.476Z")
                }
        ],
        "board_date" : ISODate("2017-07-11T12:19:26.023Z"),
        "__v" : 0
}

router/index.js

var express = require('express');
var router = express.Router();

var Board = require('../models/board');
var Comment = require('../models/comment');

/* GET home page. */
router.get('/', function(req, res, next) {
  Board.find({}, function (err, board) {
      res.render('index', { title: 'Express', board: board });
  });
});

/* Write board page */
router.get('/write', function(req, res, next) {
    res.render('write', { title: '글쓰기' });
});

/* board insert mongo */
router.post('/board/write', function (req, res) {
  var board = new Board();
  board.title = req.body.title;
  board.contents = req.body.contents;
  board.author = req.body.author;

  board.save(function (err) {
    if(err){
      console.log(err);
      res.redirect('/');
    }
    res.redirect('/');
  });
});

/* board find by id */
router.get('/board/:id', function (req, res) {
    Board.findOne({_id: req.params.id}, function (err, board) {
        res.render('board', { title: 'Board', board: board });
    })
});

/* comment insert mongo*/
router.post('/comment/write', function (req, res){
    var comment = new Comment();
    comment.contents = req.body.contents;
    comment.author = req.body.author;

    Board.findOneAndUpdate({_id : req.body.id}, { $push: { comments : comment}}, function (err, board) {
        if(err){
            console.log(err);
            res.redirect('/');
        }
        res.redirect('/board/'+req.body.id);
    });
});

module.exports = router;


view/index.ejs body 태그

root 페이지로 보낸 board를 받아 제목을 뿌려줍니다.

제목의 href로 board의 _id값을 붙여 id로 board를 find할 수 있도록 합니다.

    

<%= title %>

Welcome to <%= title %>

글쓰기
<% if (board !== null){ for(var i = 0; i < board.length; i++) { %>

<%= i+1 %> - <%=board[i].title%>

<% }} %>


view/write.ejs body 태그

<%= title %>

Welcome to <%= title %>

제목 :
내용 :
글쓴이 :


view/board.ejs body 태그

board의 id로 찾아온 board 객체를 뿌려줍니다.

board 안에 comment 데이터가 존재할 경우 같이 뿌려줄 수 있도록 구현햇습니다.

<%= title %>

Welcome to <%= title %>

제목 : <%=board.title%>

작성자 : <%=board.author%>

내용 : <%=board.contents%>


<% if (board.comments !== null) { var comment = board.comments; for(var i = 0; i < board.comments.length; i++) {%>

작성자 : <%=comment[i].author%>

내용 : <%=comment[i].contents%>


<%}}%> 댓글 :
글쓴이 :


결과

< 메인화면 >

< 글쓰기 화면 >

< 글 상세보기 화면 >