📝

node에서의 mongoose

복잡도를 줄이기 위해 CR만 수행합니다. UD의 원리도 다르지 않습니다. 아래 3개의 파일만 수정하면 되기 때문에 이해가 안될 경우 손코딩을 권고해드립니다.
앞에서 했었던 Node blog project를 mongoose와 연동해보도록 하겠습니다.
// app.js // npm init --yes // npm i nunjucks express cors helmet morgan nunjucks-date-filter mongoose // npm i nodemon --save-dev // -> nodemon app1 으로 실행 가능 // 시나리오 // postman test data // post : localhost:8080/blog // post, body, raw, json, data(아래) 확인 후 send // title1부터 title3까지 // { // "title" : "title1", // "content" : "content1", // "section" : "section1" // } // send 후 아래 url로 접속하면 4번이 들어와있는 것 확인 // localhost:8080/blog const nunjucks = require('nunjucks'); const express = require('express'); const cors = require('cors'); const morgan = require('morgan'); const helmet = require('helmet'); const blogRouter = require('./router/blog.js'); const dateFilter = require('nunjucks-date-filter'); const path = require('path'); const app = express(); app.set('view engine', 'html'); 경로 = path.join(path.join(__dirname + '/resource'), '/static'); console.log(경로); app.use('/', express.static(경로)); app.use('/blog', express.static(경로)); let env = nunjucks.configure('resource/template', { autoescape: true, express: app, watch: true }); env.addFilter('date', dateFilter); app.use(express.json()); app.use(helmet()); app.use(cors()); app.use(morgan('tiny')); app.get('/', (req, res, next) => { const data = blogRouter.blogs; // const data = blogRouter.blogs.slice(0, 3); res.render('index.html', {data}); }); app.get('/about', (req, res, next) => { res.render('about.html'); }); app.use('/blog', blogRouter); app.get('/contact', (req, res, next) => { res.render('contact.html'); }); app.use((req, res, next) => { res.sendStatus(404); }) app.use((err, req, res, next) => { console.log('애러났음!') console.log(err); res.sendStatus(500); }) app.listen(8080);
 
  • router에 blog.js 파일입니다. 변경된 사항들 잘 확인해야 합니다. DB에서 데이터를 읽어와야 글을 읽을 수 있기 때문에 promise를 사용했습니다.
const express = require('express'); const blogdatabase = require('../data/blogdatabase.js'); // let blogs = [{ // id : 1, // title : 'title1', // content : 'content1', // section : 'section1', // pubDate : new Date().toString(), // modDate : new Date().toString() // }, { // id : 2, // title : 'title2', // content : 'content2', // section : 'section2', // pubDate : new Date().toString(), // modDate : new Date().toString() // }, { // id : 3, // title : 'title3', // content : 'content3', // section : 'section3', // pubDate : new Date().toString(), // modDate : new Date().toString() // }]; const router = express.Router(); router.get('/', (req, res, next) => { console.log(req.query); const section = req.query.section; // DB가 비동기 이기 때문에 아래 코드도 비동기로 수정해주셔야 합니다. section ? blogdatabase.findBySection(section) .then(data => res.render('post.html', {data})) : blogdatabase.getAll() .then(data => res.render('post.html', {data})); // const data = section ? blogs.filter(b => b.section === section) : blogs; // 아래처럼 수정하면 안됨, 비동기 이기 때문에 // const data = section ? blogdatabase.findByTitle(section) : blogdatabase.getAll(); // console.log(data); // res.render('post.html', {data}); }) router.get('/:id', (req, res, next) => { const id = req.params.id; blogdatabase.findById(id) .then(blog => res.render('postdetails.html', {blog})); // const blog = blogs.find(b => b.id == id); //타입이 number, string // res.render('postdetails.html', {blog}); }) router.post('/', (req, res, next) => { // 스키마 // title: { type: String, required: true }, // content: { type: String, required: true }, // section: { type: String, required: true }, // pubDate: { type: Date, default: Date.now }, // modDate: { type: Date, default: Date.now }, const title = req.body.title; // const {key1, key2...} = req.body; const content = req.body.content; const section = req.body.section; let blog = {title, content, section}; const id = blogdatabase.createBlog(blog); // blogs.push(blog); res.status(201).json({id}); // 201은 create }) router.put('/:id', (req, res, next) => { const id = req.params.id; const blog = blogdatabase.findById(id); // const blog = blogs.find(b => b.id == id) if (blog){ // 각각의 값이 비어있을 수도 있음 res.status(200).json(blog); } else { res.status(404); } }) // 삭제(DELETE) : blog/:id // router.delete('/:id', (req, res, next) => { // const id = req.params.id; // blogs = blogs.filter(b => b.id != id) // res.status(200).json(blogs); //굳이 204를 보내줄거면 200로 // }) module.exports = router; module.exports['blogs'] = blogdatabase.getAll(); // 좋은 방법은 아닙니다. DB 할 때 다시 리펙토링 해야합니다.
 
  • data폴더에 blogdatabase.js 파일입니다. 새로 생성한 파일입니다.
const mongoose = require('mongoose'); // 1. DB세팅, url뒤에 project 주소로 자동 생성됨 // mongodb://[id:pw]localhost:27017/[project]의 형태 mongoose.connect('mongodb://localhost:27017/test111'); // 2. 연결 DB 사용 const db = mongoose.connection; // 3. 연결 실패 db.on('error', function(){ console.log('연결 실패'); }); // 4. 연결 성공 db.once('open', function() { console.log('연결 성공'); }); // id : 3, // title : 'title3', // content : 'content3', // section : 'section3', // pubDate : new Date().toString(), // modDate : new Date().toString() const blogSchema = new mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, section: { type: String, required: true }, pubDate: { type: Date, default: Date.now }, modDate: { type: Date, default: Date.now }, }); // 6. 정의된 스키마를 컴파일(객체처럼 사용하기 위해 model() 함수로 컴파일) const Blog = mongoose.model('Schema', blogSchema); async function findByTitle(title) { return Blog.find({ title }); } async function findBySection(section) { console.log('데이터 찾기 section'); return Blog.find({ section }); } async function findById(id) { console.log('데이터 찾기 id'); return Blog.findById(id); } async function createBlog(blog) { console.log('데이터 생성') return new Blog(blog).save().then((blog) => blog._id); } async function getAll() { console.log('데이터 모두 출력'); return Blog.find({}); // Blog.find({}, function(error, blog){ // console.log('-- 데이터 읽기 시작 --'); // if (error) { // console.log(error); // } else { // console.log(blog); // } // console.log('-- 데이터 읽기 끝 --'); // }); } module.exports = {findByTitle, findBySection, findById, createBlog, getAll}