contents.js 5.02 KB
var express = require('express');
var BoardContents = require('../models/boardsSchema'); //db를 사용하기 위한 변수
var fs = require('fs');
var router = express.Router();

router.get('/', function(req,res){
    // 처음 index로 접속 했을시 나오는 부분
    // db에서 게시글 리스트 가져와서 출력
    // pagination 추가 -> 11/17
    // page는 1-5까지 보여줌 -> db에서 총 갯수 잡아와서 10으로 나눠서 올림해야함
    // 한페이지에 10개의 게시글: limit: 10, skip: (page-1)*10 이면 될 듯
    // page number는 param으로 받아오기 가장 처음엔 param 없으니까 그땐 자동 1로 설정

    var page = req.param('page');
    if(page == null) {page = 1;}

    var skipSize = (page-1)*10;
    var limitSize = 10;
    var pageNum = 1;


    BoardContents.count({},function(err, totalCount){
       // db에서 날짜 순으로 데이터들을 가져옴
        if(err) throw err;

        pageNum = Math.ceil(totalCount/limitSize);
        BoardContents.find({}).sort({average:-1}).skip(skipSize).limit(limitSize).exec(function(err, pageContents) {
            if(err) throw err;
            res.render('board', {title: "Board", page : page, contents: pageContents, pagination: pageNum, searchWord: ''});
        });
    });
});

router.get('/search', function(req, res){
    // 글 검색하는 부분
    var search_word = req.param('searchWord');
    var search_company = req.param('company');
    var search_category = req.param('category');
    var searchCondition = {$regex:''};
    var searchCompany = {$regex:''};
    var searchCategory = {$regex:''};

    if(search_word!='')
      searchCondition = {$regex:search_word};
    if(search_company!='all')
      searchCompany = {$regex:search_company};
    if(search_category!='all')
      searchCategory = {$regex:search_category};

    var page = req.param('page');
    if(page == null) {page = 1;}
    var skipSize = (page-1)*10;
    var limitSize = 10;
    var pageNum = 1;


    BoardContents.count({$and:[{name:searchCondition},{company:searchCompany},{category:searchCategory}]},function(err, searchCount){
        if(err) throw err;
        pageNum = Math.ceil(searchCount/limitSize);

        BoardContents.find({$and:[{name:searchCondition},{company:searchCompany},{category:searchCategory}]}).sort({average:-1}).skip(skipSize).limit(limitSize).exec(function(err, searchContents){
            if(err) throw err;

            res.render('board', {title: "Board", page : page,contents: searchContents, pagination: pageNum, searchWord: search_word});
        });
    });
});


router.post('/', function(req, res){
    //field name은 form의 input file의 name과 같아야함
    // 글 작성하고 submit하게 되면 저장이 되는 부분
    // 글 수정하고 submit하면 수정된 결과가 저장되는 부분
    var mode = req.param('mode');

    var addNewName = req.body.addContentName;
    var addNewCompany = req.body.addContentCompany;
    var addNewCategory = req.body.addContentCategory;
    var addNewPrice = req.body.addContentPrice;

    if(mode == 'add') {
          addBoard(addNewName, addNewCompany, addNewCategory, addNewPrice);
          res.redirect('/boards');
    }
});

router.post('/reply', function(req, res){
    // 댓글 다는 부분
    var reply_grade = req.body.replyGrade;
    var reply_comment= req.body.replyComment;
    var reply_id = req.body.replyId;

    addComment(reply_id, reply_grade, reply_comment,function(){
          res.redirect('/boards/view?id='+reply_id);
    });

});


router.get('/view', function(req, res){
    // 글 보는 부분. 글 내용을 출력하고 조회수를 늘려줘야함
    // 댓글 페이지 추가 해줌, 5개씩 출력함

    var contentId = req.param('id');

    BoardContents.findOne({_id:contentId}, function(err, rawContent){
        if(err) throw err;

        rawContent.save(function(err){
            if(err) throw err;

            res.render('boardDetail',{title: "Board", content:rawContent});
        });
    })
});



module.exports = router;

function addComment(id, grade, comment,callback) {
    BoardContents.findOne({_id: id}, function(err, rawContent){
        if(err) throw err;
        var sum = 0;
        rawContent.comments.unshift({grade:grade, memo: comment});
        for(var j = 0;j<rawContent.comments.length;j++)
        {
          sum += rawContent.comments[j].grade;
        }
        rawContent.average = sum/rawContent.comments.length;
        rawContent.save(function(err){
            if(err) throw err;
            else callback();
        });
    });
}
function addBoard(name, company, category, price){

    var newBoardContents = new BoardContents;
    newBoardContents.name = name;
    newBoardContents.company = company;
    newBoardContents.category = category;
    newBoardContents.price = price;
    newBoardContents.average = 0;

    newBoardContents.save(function (err) {
        if (err) throw err;
        BoardContents.findOne({_id: newBoardContents._id}, {_id: 1}, function (err, newBoardId) {
            if (err) throw err;
          })
        });
    }