쿼리 수행하기
views 폴더 안에 html을 만들어 보자.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>몽구스 서버</title>
<style>
table { border: 1px solid black; border-collapse: collapse; }
table th, table td { border: 1px solid black;}
</style>
</head>
<body>
<div>
<form id="user-form">
<fieldset>
<legend>사용자 등록</legend>
<div><input id="username" type="text" placeholder="이름"></div>
<div><input id="age" type="number" placeholder="나이"></div>
<div><input id="married" type="checkbox"><label for="married">결혼 여부</label></div>
<button type="submit">등록</button>
</fieldset>
</form>
</div>
<br>
<table id="user-list">
<thead>
<tr>
<th>아이디</th>
<th>이름</th>
<th>나이</th>
<th>결혼여부</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>{{ '기혼' if user.married else '미혼' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<div>
<form id="comment-form">
<fieldset>
<legend>댓글 등록</legend>
<div><input id="userid" type="text" placeholder="사용자 아이디"></div>
<div><input id="comment" type="text" placeholder="댓글"></div>
<button type="submit">등록</button>
</fieldset>
</form>
</div>
<br>
<table id="comment-list">
<thead>
<tr>
<th>아이디</th>
<th>작성자</th>
<th>댓글</th>
<th>수정</th>
<th>삭제</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="/mongoose.js"></script>
</body>
</html>
views/mongoose.html
<h1>{{ message }}</h1>
<h2>{{ error.status }}</h2>
<pre>{{ error.stack }}</pre>
views/error.html
이제 js파일을 만들어서 서버를 돌려보자.
//사용자 이름을 클릭할 때 댓글 로딩
document.querySelectorAll('#user-list tr').forEach((el) => {
el.addEventListener('click', function(){
const id = el.querySelector('td').textContent;
getComment(id);
});
});
//사용자 로딩
async function getUser(){
try{
const res = await axios.get('/users');
const users = res.data;
console.log(users);
const tbody = document.querySelector('#user-list tbody');
tbody.innerHTML = '';
users.map(function(user){
const row = document.createElement('tr');
row.addEventListener('click', () => {
getComment(user._id);
});
let td = document.createElement('td');
td.textContent = user._id;
row.appendChild(td);
td = document.createElement('td');
td.textContent = user.name;
row.appendChild(td);
td = document.createElement('td');
td.textContent = user.age;
row.appendChild(td);
td = document.createElement('td');
td.textContent = user.married ? '기혼' : '미혼';
row.appendChild(td);
tbody.appendChild(row);
});
}catch(err){
console.error(err);
}
}
//댓글로딩
async function getComment(id){
try{
const res = await axios.get(`/users/${id}/comments`);
const comments = res.data;
const tbody = document.querySelector('#comment-list tbody');
tbody.innerHTML = '';
comments.map(function(comment){
//로우 셀 추가
const row = document.createElement('tr');
let td = document.createElement('td');
td.textContent = comment._id;
row.appendChild(td);
td = document.createElement('td');
td.textContent = comment.commenter.name;
row.appendChild(td);
td = document.createElement('td');
td.textContent = comment.comment;
row.appendChild(td);
const edit = document.createElement('button');
edit.textContent = '수정';
//수정 클릭시
edit.addEventListener('click', async () => {
const newComment = prompt('바꿀 내용을 입력하세요');
if(!newComment){
return alert('내용을 입력하세요');
}
try{
await axios.patch(`/comments/${comment._id}`, { comment: newComment });
getComment(id);
}catch(err){
console.error(err);
}
});
const remove = document.createElement('button');
remove.textContent = '삭제';
//삭제 클릭시
remove.addEventListener('click', async () => {
try{
await axios.delete(`/comments/${comment._id}`);
getComment(id);
}catch(err){
console.error(err);
}
});
//버튼 추가
td = document.createElement('td');
td.appendChild(edit);
row.appendChild(td);
td = document.createElement('td');
td.appendChild(remove);
row.appendChild(td);
tbody.appendChild(row);
});
}catch(err){
console.error(err);
}
}
//사용자 등록시
document.getElementById('user-form').addEventListener('submit', async(e) => {
e.preventDefault();
const name = e.target.username.value;
const age = e.target.age.value;
const married = e.target.married.checked;
if(!name){
return alert('이름을 입력하세요');
}
if(!age){
return alert('나이을 입력하세요');
}
try{
await axios.post('/users', {name, age, married });
getUser();
}catch(err){
console.error(err);
}
e.target.username.value = '';
e.target.age.value = '';
e.target.married.checked = false;
});
//댓글 등록시
document.getElementById('comment-form').addEventListener('submit', async(e) => {
e.preventDefault();
const id = e.target.userid.value;
const comment = e.target.comment.value;
if(!id){
return alert('아이디를 입력하세요');
}
if(!comment){
return alert('댓글을 입력하세요');
}
try{
await axios.post('/comments', {id, comment});
getComment(id);
}catch(err){
console.error(err);
}
e.target.userid.value = '';
e.target.comment.value = '';
});
public/mongoose.js
마지막으로 라우터를 작성해보자.
const express = require('express');
const User = require('../schemas/user');
const router = express.Router();
router.get('/', async(req, res, next) => {
try{
const users = await User.find({});
res.render('mongoose', {users});
}catch(err){
console.error(err);
next(err);
}
});
module.exports = router;
routes/index.js
const express = require('express');
const User = require('../schemas/user');
const Comment = require('../schemas/comment');
const router = express.Router();
router.route('/')
.get(async(req, res, next) =>{
try{
const users = await User.find({});
res.json(users);
}catch(err){
console.error(err);
next(err);
}
})
.post(async(req, res, next) => {
try{
const user = await User.create({
name: req.body.name,
age: req.body.age,
married: req.body.married,
});
console.log(user);
res.status(201).json(user);
}catch(err){
console.error(err);
next(err);
}
});
router.get('/:id/comments', async(req, res, next) => {
try{
const comments = await Comment.find({commenter: req.params.id})
.populate('commenter');
console.log(comments);
res.json(comments)
}catch(err){
console.error(err);
next(err)
}
});
module.exports = router;
routes/users.js
const express = require('express');
const Comment = require('../schemas/comment');
const router = express.Router();
router.post('/', async(req, res, next) => {
try{
console.log(req.body.id);
console.log(req.body.comment);
const comment = await Comment.create({
commenter: req.body.id,
comment: req.body.comment,
});
console.log(comment);
const result = await Comment.populate(comment, {path: 'commenter'});
res.status(201).json(result);
}catch(err){
console.error(err);
next(err);
}
});
router.route('/:id')
.patch(async (req, res, next) => {
try{
const result = await Comment.updateOne({
_id: req.params.id,
},{
comment: req.body.comment,
});
res.json(result);
}catch(err){
console.error(err);
next(err);
}
})
.delete(async (req, res, next) => {
try{
const result = await Comment.remove({_id: req.params.id});
res.json(result);
}catch(err){
console.error(err);
next(err);
}
});
module.exports = router;
routes/comment.js
서버를 시작시켜보자.