티스토리 뷰

- 최종적으로 만드려는 API의 흐름은 아래와 같다.

1. 사용자가 '/list' URL로 GET 요청
2. MongoDB에서 데이터를 꺼낸다.
3. 꺼낸 데이터를 list.ejs 파일에 꽂아넣은 후 사용자에게 보내준다.

● MongoDB에서 데이터 꺼내기(collection.find)

- 현재 post collection에 저장돼있는 데이터는 아래와 같다.

현재 DB에 저장돼있는 데이터들

db.collection('post').find() 
db.colleciton('post').findOne()

- 위와 같은 코드를 이용해 DB에 있는 데이터를 꺼낼 수 있다. 
- 만약 post collection에 저장된 모든 데이터를 가져오고 싶으면 아래와 같이 코드를 짜면 된다.

(server.js)
app.get('/list', (req, res) => {
    // post collection 안에 저장된 모든 데이터를 꺼내라
    db.collection('post').find().toArray(function(error, result) {
        console.log(result);
        res.render('list.ejs');
    })
});

.find().toArray() function을 통해 collection('post')에 있는 모든 데이터를 Array 자료형으로 가져올 수 있다. 

- [자료1, 자료2 ...]  →  이런 식으로 담긴다. 

- 만약 자료들이 안오거나 error가 나면 실제 DB에 데이터가 제대로 저장되어 있는지 확인해보자 
- DB 데이터가 오염됐거나 그러면 원하는대로 보이지 않을 수 있다.

콘솔에 출력된 데이터

 

cf)

- 아래의 코드만 작성해도 DB의 모든 데이터를 가져올 수 있다.

- 근데 이렇게 가져오면 데이터에 포함된 metadata까지 다 가져와버리므로 toArray function 같은 걸 사용하는 것이다.

app.get('/list', (req, res) => {
    db.collection('post').find();
});

console.log(db.collection('post').find());


● DB에서 찾아온 데이터를 list.ejs 파일에 넣기

- DB에서 가져온 데이터를 list.ejs 파일에 꽂아주면 사용자가 해당 데이터를 볼 수 있게 된다.

app.get('/list', (req, res) => {
    db.collection('post').find().toArray(function(error, result) {
        // 1. DB에서 자료를 찾아라
        // 2. 찾은 자료를 list.ejs 파일에 넣어라
        console.log(result);
        res.render('list.ejs', {posts : result});
    });
});

- .render() function의 두 번째 parameter를 위와 같이 적으면 list.ejs 파일을 렌더링함과 동시에 {posts: result} 라는 데이터를 함께 보내줄 수 있다.
- 정확히 말하면 'result'라는 데이터를 'posts'라는 이름으로 ejs 파일에 보내는 것이다.(key:value = posts:result)
- 이제 가져온 데이터를 list.ejs 파일에 집어넣어보자

(views/list.ejs)
<h4><%= posts %></h4>
<p><%= posts %></p>

<h4>임시 제목</h4>
<p>임시 날짜</p>

localhost:8080/list

- <%= posts %>까지만 작성해도 화면에 데이터가 나온 것을 확인할 수 있다.
- 'result'라는 데이터(value)를 'posts'라는 이름(key)으로 list.ejs 파일에 넣어준 것이다.
- 하지만 [object Object] 같은 모양을 사용자에게 보여줄 수는 없으니 원하는 제목과 날짜 데이터를 보여주려면 아래와 같이 코드를 수정하면 된다.

(views/list.ejs)
<h4><%= posts[0].title %></h4>
<p><%= posts[0].date %></p>

<h4><%= posts[1].title %></h4>
<p><%= posts[1].date %></p>

cf) 만약 error가 발생하면 실제 DB에 데이터가 몇 개 저장돼 있는지 확인해보자

- mongoDB에 2개의 데이터가 저장돼 있을 때 일부러 아래와 같이 ejs 파일을 작성하면 오류가 발생한다.

(views/list.ejs)
<h4><%= posts[0].title %></h4>
<p><%= posts[0].date %></p>

<h4><%= posts[2].title %></h4>
<p><%= posts[2].date %></p>

- /list로 GET 요청을 해보니 아래와 같은 오류 메세지가 나왔다.

- Array의 범위를 넘어서 참조했기에 undefined 메세지가 나오는 것이다.


● HTML에 for 문을 적용해 리스트 여러개 만들기

- EJS에서 javascript를 사용하는 것이니 '<% %>' 내부에 JS 코드를 담아야한다.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <title>ToDo list</title>
</head>
<body>
    <div class="pos-f-t">
        <div class="collapse" id="navbarToggleExternalContent">
        <div class="bg-dark p-4">
            <h5 class="text-white h4">Collapsed content</h5>
            <span class="text-muted">Toggleable via the navbar brand.</span>
        </div>
        </div>
        <nav class="navbar navbar-dark bg-dark">
            <h5 class="text-white h4">ToDo!!!</h5>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
        </nav>
    </div>

    <h4 class="container mt-4"><strong>서버에서 가져온 ToDo list</strong></h4>

    <% for(let i = 0; i < posts.length; i++) { %>
      <h4><%= posts[i].title %></h4>
      <p><%= posts[i].date %></p>
    <% } %>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
</body>
</html>
[핵심은 아래 부분]

<% for(let i = 0; i < posts.length; i++) { %>
    <h4><%= posts[i].title %></h4>
    <p><%= posts[i].date %></p>
<% } %>

http://localhost:8080/list로 접속한 모습

 

cf) server.js

const express = require('express'); // 첨부
const app = express(); // 사용

const MongoClient = require('mongodb').MongoClient;
app.set('view engine', 'ejs'); // ejs를 사용하겠다고 명시하는 부분

var db;
MongoClient.connect('접속URL', client) { // callback function
    if(error) return console.log(error);

    // 어떠한 DB를 사용할 것인지 명시
    db = client.db('todoapp'); // todoapp database에 연결해라

    // db.collection('post') --> 여러개의 collection 중 post 라는 이름의 collection을 선택한다는 뜻
    // db.collection('post').insertOne({name:"John2", _id : 200}, function(error, result) {
    //     console.log('저장완료');
    // });

    // 서버띄우는 코드 여기로 옮겨야 함
    app.listen(8080, function() { // (웹서버를 오픈하고 싶은 포트 번호, 오픈 후 callback function)
        console.log('server on : listening on 8080');
    });
}); // MongoClient.connect(DB 접속이 완료되면, callback function 실행)

app.use(express.urlencoded({extended: true}));

app
.get("/", (req, res) => { // {"/", (req, res) = 경로, (요청내용, 응답할 방법)}
    res.sendFile(__dirname + '/index.html'); // .sendFile(보낼파일경로)
})
.get('/pet', (req, res) => { // app.get(경로, callback function)
    res.send("펫용품 사라고");
})
.get('/beauty', (req, res) => {
    res.send("뷰티용품 사라고");
})
.get("/write", (req, res) => {
    res.sendFile(__dirname + '/write.html');
})
.post("/add", (req, res) => { // <input>에 담겨있는 정보는 req에 들어있다.
    // collection 중 post collection 선택
    db.collection('post').insertOne({title : req.body.title, date : req.body.date}, (error, result) => {
        console.log(req.body);
    });
    res.send("전송완료");
})
.get('/list', (req, res) => {
    // post collection 안에 저장된 모든 데이터를 꺼내라
    console.log(db.collection('post').find()); 
    db.collection('post').find().toArray(function(error, result) {
        // 1. DB에서 자료를 찾아라
        // 2. 찾은 자료를 list.ejs 파일에 넣어라
        console.log(result);
        res.render('list.ejs', {posts : result});
    });
});
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함