카테고리 없음

[Node.js]MongoDB로 CRUD 구현하기

채영채영 2023. 11. 15. 03:05

CRUD : Create, Read, Update, Delete

main page에서 GET 요청을 하였으며, url 에선 /로 구분

write page는 /write

detail page는 /detail

edit page는 /edit

write.html파일 수정 ↓

{% extends 'base.html' %}

{% block content %}
<h1>글 작성 페이지입니다.</h1>
<form action="/write" method="post">
    <label for="title">제목</label>
    <input type="text" name="title" id="title">
    <br>
    <label for="contents">내용</label>
    <textarea name="contents" id="contents" cols="20" rows="5"></textarea>
    <br>
    <label for="date">날짜</label>
    <input type="date" name="date" id="date">
    <br>
    <!-- input submit -->
    <input type="submit" value="글 작성 완료">
</form>
{% endblock %}

 

데이터베이스의 종류 : 관계형, 비관계형

관계형 : SQL, 비관계형: NoSQL (MongoDB)

MongoDB 
- 문서 지향적 데이터베이스
- 데이터 구조가 하나 이상의 key:value 쌍으로 이루어짐, 모든 데이터가 JSON형태로 저장
- Collection : Document 그룹 단위

macos환경이 아니므로GUI로 MongoDB 설치
https://ozofweird.tistory.com/entry/MongoDB-MongoDB-%EC%84%A4%EC%B9%98 참고

  • brew tap mongodb/brew
  • brew install mongodb/brew/mongodb-community
  • brew services start mongodb-community
  • brew services list
  • brew install mongodb-community-shell
  • npm i mongoose 
  •  

<Mongoose>

- Schema : Node.js에서 데이터 처리를 쉽게 해줄 수 있는 스키마 제공
- Schema 종류 : String, Number, Date, Boolean, Buffer, Mixed(모든 데이터 타입 가능), ObjectedID(객체 ID), Array(배열)

//mongoose set
const { Schema } = mongoose;

const WritingSchema = new Schema({
    title: String,
    contents: String,
    date: {
        type: Date,
        default: Date.now,
    }

})

import express from 'express';
import nunjucks from 'nunjucks';
import bodyParser from 'body-parser';
import path from 'path';
import fs from 'fs';
import mongoose from 'mongoose';

const app = express();

const __dirname = path.resolve()

const filePath = path.join(__dirname, 'data', 'writing.json');

// body parser set
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json());

// view engine set
app.set('view engine', 'html'); // main.html -> main(.html)

// nunjucks
nunjucks.configure('views', {
    watch: true, 
    express: app
})

mongoose
    .connect('mongodb://127.0.0.1:27017')
    .then(() => console.log('DB connect'))
    .catch(e => console.error(e));

const {Schema} = mongoose;

const WritingSchema = new Schema({
    title:String,
    contents: String,
    date:{
        type:Date,
        default: Date.now,
    }
})

const Writing = mongoose.model('Writing', WritingSchema);

// middleware
// main page GET
app.get('/', async (req, res) => {
    const fileData = fs.readFileSync(filePath);
    const writings = JSON.parse(fileData);
    res.render('main', { list: writings});

});

app.get('/write', (req, res) => {
    res.render('write');
});

app.post('/write', async (req, res) => {
    const title = req.body.title;
    const contents = req.body.contents;
    const date = req.body.date;

    const fileData = fs.readFileSync(filePath);
    

    const writings = JSON.parse(fileData);
    
    writings.push({
        'title':title,
        'contents': contents,
        'date': date
    });

    fs.writeFileSync(filePath, JSON.stringify(writings));

    res.render('detail', { 'detail': { title: title, contents: contents, date: date } });
});

app.get('/detail', async (req, res) => {
    res.render('detail');
})

app.listen(3000, () => {
    console.log('Server is running');
});
​
 

{% extends 'base.html' %}

{% block content %}
<h1>write page.</h1>
<form action="/write" method="post">
    <label for="title">title</label>
    <input type="text" name="title" id="title">
    <br>
    <label for="contents">content</label>
    <textarea name="contents" id="contents" cols="20" rows="5"></textarea>

    <!-- input submit -->
    <input type="submit" value="finish to write">
</form>
{% endblock %}

=> base.html

 

import express from 'express';
import nunjucks from 'nunjucks';
import bodyParser from 'body-parser';
import path from 'path';
import fs from 'fs';
import mongoose from 'mongoose';

const app = express();

const __dirname = path.resolve()

const filePath = path.join(__dirname, 'data', 'writing.json');

// body parser set
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// view engine set
app.set('view engine', 'html'); // main.html -> main(.html)

// nunjucks
nunjucks.configure('views', {
    watch: true,
    express: app
})

mongoose
    .connect('mongodb://127.0.0.1:27017')
    .then(() => console.log('DB connect'))
    .catch(e => console.error(e));

const {Schema} = mongoose;

const WritingSchema = new Schema({
    title:String,
    contents: String,
    date:{
        type:Date,
        default: Date.now,
    }
})

const Writing = mongoose.model('Writing', WritingSchema);

// middleware
// main page GET
app.get('/', async (req, res) => {
    const fileData = fs.readFileSync(filePath);
    const writings = JSON.parse(fileData);
    res.render('main', { list: writings});

});

app.get('/write', (req, res) => {
    res.render('write');
});

app.post('/write', async (req, res) => {
    const title = req.body.title;
    const contents = req.body.contents;
    const date = req.body.date;

    const fileData = fs.readFileSync(filePath);
   

    const writings = JSON.parse(fileData);
   
    writings.push({
        'title':title,
        'contents': contents,
        'date': date
    });

    fs.writeFileSync(filePath, JSON.stringify(writings));

    res.render('detail', { 'detail': { title: title, contents: contents, date: date } });
});

app.get('/detail', async (req, res) => {
    res.render('detail');
})

app.listen(3000, () => {
    console.log('Server is running');
});

=> index.js

{% extends 'base.html' %}

{% block content %}
    {% if detail %}
        <h1>상세 페이지</h1>
        <p>글 제목: {{ detail.title }}</p>
        <p>글 내용: {{ detail.contents }}</p>
        <a href="/edit/{{ detail.id }}" class="btn">글 수정</a>
        <form action="/delete/{{ detail.id }}" method="post">
                        <input type="submit" value="글 삭제">
                </form>
    {% else %}
        <h1>상세 페이지 수정</h1>
        <form action="/edit/{{ edit.id }}" method="post">
            <p>글 제목: <input type="text" name="title" value="{{ edit.title }}"></p>
            <p>글 내용: <input type="text" name="contents" value="{{ edit.contents }}"></p>
            <input type="submit" value="수정 완료">
        </form>
    {% endif %}
{% endblock %}

=> 삭제 detail.html

(어느 순간 크래시가 나서 페이지 확인이 안된다 )하하))머쓱))