먼저 글을 입력할 수 있는 입력란이 있어야 할거 같다.
ejs파일을 통해서 write.ejs에서 폼태그를 통해 글 작성란을 만들었다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>list</title>
<link href="/main.css" rel="stylesheet">
</head>
<body class="grey-bg">
<%- include('nav.ejs')%>
<form class="form-box" action="/newPost" method="POST">
<h4>글쓰기</h4>
<input name="title">
<input name="content">
<button type="submit">전송</button>
</form>
</body>
</html>
이렇게 작성을 해주고 server.js 파일 쪽에서
app.post('/newPost', async (req, resp) =>{
let title = req.body.title
let content = req.body.content
try{
if ( title == '' || content == ''){
resp.send('빈칸은 안됨')
}else{
await db.collection('post').insertOne({title: title, content : content})
resp.redirect('/list')
}
}catch(e){
console.log(e)
resp.status(500).send('서버가 안됨')
}
})
해당 데이터들을 req 바디 태그안에 값들을 불러서 변수에 담아주었다.
그리고 try catch문 안에 코드들을 작성해주어 혹시 모를 예외상황을 잡아내게 하였다.
여기서 insertOne을 사용할 땐 키 : 밸류 값으로 데이터 값을 인서트 해주어야한다.
그리고 글 목록 페이지로 다시 리다이렉트~
아주 간단하다..
내가 셋팅 해둔 mongodb안에 데이터 값이 잘 들어간 모습이다.