const router = express.Router({mergeParams: true});
app.use("/posts/:id/comments", commentsRouter);
router.post('/', checkAuthenticated, async (req, res) => {
// app.js에서 router 경로를 정의 해줬기 때문에 여기서는 할 필요가 없다.
// 그런데 post를 찾으려면 req.params.id를 가져와야 하는데 app.js router 경로에 있기 때문에
// 여기서는 사용이 불가능하다. 그때 const router = express.Router({mergeParams: true}); 설정 해주면 된다.
const post = await Post.findById(req.params.id);
let text = req.body.text
if (post) {
Comment.create({
text,
author: {
id: req.user._id,
username: req.user.username
}
}).then((comment) => {
console.log(comment)
post.comments.push(comment)
post.save()
req.flash('success', '댓글이 생성되었습니다.')
res.redirect('/posts')
}).catch((error) => {
console.log(error)
req.flash('error', '댓글 생성이 실패했습니다.')
res.redirect('/posts')
})
} else {
req.flash('error', '포스트가 존재하지 않습니다.')
res.redirect('/posts')
}
})