Project/축구모임 홈페이지개발
[축구모임 홈페이지개발] 03/23 개발일지 Nodejs / 게시물 댓글 개수 표시
한33
2024. 3. 23. 16:03
다른 사이트들을 참고하던 중에 게시판에서 제목 뒤에 해당 게시물의 댓글 개수가 표시되는 기능이 있다.
게시물에 댓글이 추가되었는지도 들어가지 않고 확인할 수 있고
여러모로 필요한 기능 같아서 추가하고자 했다.
app.get('/notice/:number', async (req, res) => {
let result = await db.collection('notice').find().sort({ _id: -1 }).skip((req.params.number - 1) * 10).limit(10).toArray();
let result2 = await db.collection('notice').find().sort({ _id: -1 }).toArray();
let commentCounts = [];
for (let i = 0; i < result.length; i++) {
let commentCount = await db.collection('comment').countDocuments({ parentId: result[i]._id });
commentCounts.push(commentCount);
}
res.render('notice.ejs', { 글목록: result, 글전체: result2, 댓글개수: commentCounts})
})
let commentCounts = [];
우선 댓글 수를 저장할 빈 배열을 선언해줬다.
let commentCount = await db.collection('comment').countDocuments({ parentId: result[i]._id });
commentCounts.push(commentCount);
comment 컬렉션에 접근한 다음에 countDocuments 를 이용해서 result[i]._id 가 parentId 와 동일한 값들의 개수를 센다.
그러고 처음에 지정한 commentCounts 배열에 추가해준다.
그러고 html 파일에서
[<%= 댓글개수[i] %>]
다음과 같이 표시해주면
위와 같이 해당 게시물의 댓글을 표시할 수 있다.