Home > Software design >  How to count all comments that are in the same individual post?
How to count all comments that are in the same individual post?

Time:12-15

I'm trying to count the number of comments made in a specific post but I am getting an undefined error...
The post and comments are in the mongodb.

The current Error I get in the console:
{stringValue: '"undefined"', valueType: 'string', kind: 'ObjectId', value: 'undefined', path: 'post', …}

My current code in the server-side:

//Get all amount of comments of the individual post
app.get("/:postId/comments/all", async (req, res) => {
  try {
    const comments = await Comment.countDocuments({
      post: req.params.postId,
    });
    res.send(comments);
  } catch (err) {
    res.send({ error: err });
  }
});

My current code in the client-side:

  //Get comments quantity from the server
  const getAllComments = async () => {
    const res = await axios.get(`/api/posts/${postId}/comments/all`);
    if(res.data.error){
      setComments("");
      console.log(res.data.error);
    } else {
      setComments(res.data);
    }
  };

Comment Schema:

    const Comment = new mongoose.Schema({
      post: {
        type: Schema.Types.ObjectId,
        ref: "post",
      },

What I've tried:

I've tried looking different examples on how it's done but failed.
I tried using .find(postid).count() and send it to the front-end.

It appears to be that no matter what I do, it returns me undefined.
I've been trying to play around with it but had no luck.
I'd appreciate your support on this problem.

CodePudding user response:

I was trying to use .countDocument() in the wrong route that had no :postId in there. I added in my post Schema:

     commentsCount: {
    type: Number,
    default: 0,
  },

And then when a client submits a comment to a specific post, in server-side I increment the 'commentsCount' by one and then I render it on a specific post when the page loads.

  • Related