I cannot retrieve the data even though it is stored in the database

54 views Asked by At

I created a project with mern stack, and when I try to comment on the post from the client, the comment does not appear, even though it shows me that the comment was completed successfully, and the comment is saved in the database.

In one of my attempts, I was able to make comments print on the console, but I cannot make them appear on the page

Comments should appear in the post page

PostPage.jsx:

    const { pid } = useParams();

  const currentPost = posts[0];
  useEffect(() => {
    const getPost = async () => {
      setPosts([]);
      try {
        const res = await fetch(`/api/posts/${pid}`);
        const data = await res.json();
        if(data.error) {
          showToast("Error", data.error, "error");
          return;
        }
        setPosts([data]);
      } catch (error) {
        showToast("Error", error.message, "error");
      }
    }
    getPost();
  }, [pid, setPosts, showToast]);

  useEffect(() => {
    const getComment = async () => {
      setComments([]);
      try {
        const res = await fetch(`/api/comments/${pid}/comments`);
        const data = await res.json();
        if(data.error) {
          showToast("Error", data.error, "error");
          return;
        }
        console.log([data])
        setComments([data]);
      } catch (error) {
        showToast("Error", error.message, "error");
      }
    }
    getComment();
  }, [pid, setComments, showToast]);

return (
  ...page codes

  <Flex>
  
{comments?.length >= 0 && comments?.map((comment) => {
  return <Comment 
  key={comment?._id} 
  comment={comment} 
  lastComment={comment?._id === comments[comments?.length - 1]._id}
  />
})}
</Flex>

)

comment.jsx:

import { Avatar, Divider, Flex, Text } from "@chakra-ui/react";


const Comment = ({ comment, lastComment }) => {
  return (
    <>
    <Flex gap={4} py={2} my={2} w={"full"}>
        <Avatar src={comment.userProfilePic} size={"sm"}/>
        <Flex gap={1} w={"full"} flexDirection={"column"}>
            <Flex w={"full"} justifyContent={"space-between"} alignItems={"center"}>
                <Text fontSize={"sm"} fontWeight={"bold"}>
                    {comment.username}
                </Text>
                
            </Flex>
            <Text>{comment.comment}</Text>
        </Flex>
    </Flex>
    {!lastComment ? <Divider /> : null}
    </>
  )
}

export default Comment

commentController.js

const getComments = async (req, res) => {
        const id = req.params;
        try {
            if(id) {
            const comments = await Comment.find({ postId: id }).sort({ createdAt: -1 })
            res.json(comments);
            } else {
                res.status(404).json({ message: "Comments not found!" })
            }
        } catch (error) {
            
        }
    }

commentModel.js

import mongoose from "mongoose";
const ObjectId = mongoose.Types.ObjectId;

const commentSchema = mongoose.Schema({
    postId: {
    type: ObjectId,
    ref: "Post",
    required: true,
    },
    comment: {
        type: String,
        required: true,
    },
    replies: [{
        reply: {
            type: String,
            required: true,
        },
        username: {
            type: String,
            required: true,
        },
        commentId: {
            type: ObjectId,
            required: true,
        },
    }],
    username: {
        type: String,
        required: true,
    }
}, {
    timestamps: true
})

const Comment = mongoose.model('Comment', commentSchema);

export default Comment;
0

There are 0 answers