lky473736 / forum-express

(project) Community and Forum Service with express.js and node.js
Apache License 2.0
0 stars 0 forks source link

forum-express : log 2 #2

Open lky473736 opened 6 months ago

lky473736 commented 6 months ago

forum-express : log 2

forum을 만들 테크는 아래와 같다.


log 1에서는 express의 기본 틀을 다루었다면 log 2에선 DB 세팅과 ejs 세팅 및 동작 방식 등을 정리한다.


MongoDB vs RDB (관계형 데이터베이스)

// server.js

const { MongoClient } = require('mongodb');

let db;
const url = 'MongoDB 데이터베이스랑 연결할 수 있는 url';
new MongoClient(url).connect().then((client)=>{
  console.log('DB 연결 성공');
  // client가 url에 접속해서 연결했다면 db연결이 성공한 거다
  db = client.db('forum'); // forum이라는 DB에 접속

  // 보통은 db가 연결한 후에 포트를 연다 (listen)
  // 따라서 connect().then 이후에 listen 작업
  app.listen(8080, () => {
    console.log("http://localhost:8080 에서 서버가 실행 중입니다.");
  });
}).catch((err)=>{
  console.log(err);
});

2) DB에 무언가를 저장할 때

app.get('/post', (요청, 응답) => {
    // db.collection('저장을원하는콜렉션이름').insertOne({정보들});
    // == 저장을 원하는 콜렉션에 정보들을 하나 넣는다 
    db.collection('post').insertOne({sample : 'sample'});
    // sample : 'sample'이라는 document를 post라는 collection에 넣는다
});

// 위의 기능 : /post라는 세부 페이지에 입장하면
// db.collection 중 post라는 collection에
// sample : 'sample'이라는 document를 추가해라

3) DB에 있는 자료를 불러와야 할 때

app.get('/list', async (요청, 응답) => {
    // 응답.send('db에 있던 게시물');
    // db.collection('출력을원하는콜렉션이름').find().toArray();
    // == 특정 콜렉션의 document들을 전부 찾아서 배열 형태로 반환 (async, await 필요)

    // await : 다음 줄을 실행할 때까지 기다리기 (non-blocking i/o이기 때문에 처리가 오래걸리는 코드는 처리완료를 기다리지 않고 바로 다음 줄을 시행하기 때문에)
    // 따라서 db에 있는 자료를 모으기 위하거나 찾기 위해서는 프로그램이 잠깐은 기다려야 한다
    // await 말고도 콜백이나 then 써서 사용할 수는 있으나 mongo에서 계속 await 쓰라니깐 그렇게 한다
    let postlist = await db.collection('post').find().toArray();
    // 그러면 [{}, {}, ...] 이런 형식으로 list에 저장이 된 것이다
    console.log(postlist);

    // ejs 파일을 사용자에게 보내야함
    // 응답.render('ejs 파일명') 
    응답.render('list.ejs', {글목록 : postlist});
});

ejs 세팅 및 작성 방식

lky473736 commented 6 months ago

ejs 바인딩의 예시

    <div class="white-bg">
        <div class="list-box">
        <h4> <%= 글목록[0].title %> </h4> 
        <p> <%= 글목록[0].content %> </p>
    </div>
    <div class="list-box">
        <h4> <%= 글목록[1].title %> </h4>
        <p> <%= 글목록[1].content %> </p>
    </div>
lky473736 commented 6 months ago

ejs 구문을 작성하는 방식 중 special tag는 아래와 같다


근데 만약 위 바인딩의 예시 html들이 db에 저장된 document 수대로 필요하다면 일일히 손으로 작성하기가 힘드니 ejs 문법으로 자동화한다.

<div class="white-bg">
        <%for(let i = 0; i < 글목록.length; i++){%>
            <div class="list-box"> 
                <h4><%= 글목록[i].title %></h4>
                <p><%= 글목록[i].content %></p>
            </div>
        <%}%>
/div>
<%- include ('nav.ejs') %> 
<!--nav.ejs에 있는 html 파일을 전부 여기에 복붙해라-->