-
글쓴이글
-
2022년 6월 14일 01:00 #36154
케이크참가자안녕하세요. 프로젝트 진행중 댓글수를 구현해보기 위해 이것저것 해보는중입니다. 지금 생각한 방법은 post에 commentAll이라는 값을 default 로 0으로 준 뒤, 코멘트를 작성하고 삭제한 뒤에 해당 post의 postId값을 가진 comment들을 전부 불러와서 그 배열의 length를 updateone을 이용해 넣어주는 방식입니다. 다만 아직 front가 만들어지지 않은 상황이라 테스트가 잘 안돼서 게시판에 질문 남겨봅니다 감사합니다. 아래는 코드입니다.
// 코멘트 작성: 유저확인
router.post('/detail/:postId', authMiddlewares, async (req, res) => {
let counter = await CommentCounter.findOne({ name: 'totalComment' }).exec();
counter.totalComment++;
counter.save();
const { userId } = res.locals.user;
const existingUser = await User.findOne({ _id: userId });
const commentId = counter.totalComment;
const { comment } = req.body;
const commentDate = new Date().toLocaleDateString();
const userNickname = existingUser.userNickname;
const userProfileImage = existingUser.userProfileImage;
const authorId = existingUser._id;
const postId = parseInt(req.params);if (!comment) {
res.status(400).json({ success: false, message: '내용을 입력하세요' });
}
const createdComment = await Comment.create({
commentId,
comment,
commentDate,
userNickname,
userProfileImage,
authorId,
postId,
});
const commentAll = await Comment.find({ postId: parseInt(postId) });
await Post.updateOne(
{ postId: parseInt(postId) },
{ $set: { commentAll: commentAll.length } }
);
res.status(200).json({
success: true,
message: '댓글 저장 성공',
comment: createdComment,
});
});// 코멘트 삭제: 유저확인
router.delete('/comment/:commentId', authMiddlewares, async (req, res) => {
const { commentId } = req.params;
const { userId } = res.locals.user;
const existingComment = await Comment.find({
commentId: parseInt(commentId),
});if (userId !== existingComment.authorId) {
res
.status(400)
.json({ success: false, message: '내가 쓴 댓글이 아닙니다' });
} else {
await Comment.deleteOne({ commentId: parseInt(commentId) });
const commentAll = await Comment.find({
postId: parseInt(existingComment.postId),
});
await Post.updateOne(
{ postId: parseInt(existingComment.postId) },
{ $set: { commentAll: commentAll.length } }
);
res.status(200).json({ success: true, message: '댓글 삭제 성공' });
}
});2022년 6월 14일 10:08 #36165
codingapple키 마스터그럼 글 하나에 댓글이 10만개면
글 로드할 때 마다 댓글도 10만개 전부 가져와야해서 비효율적이라
댓글총 갯수를 어디 저장해두고 댓글발행할 때 마다 +1 하거나
.count()같은거 써서 document 갯수만 세라고 하거나 하면 됩니다
-
글쓴이글
- 답변은 로그인 후 가능합니다.