Search code examples
javascriptnode.jsreactjsmongodbmongoose-schema

Failed to delete the a comment on post?


I'm trying to delete a comment on a post, but I'm unable to find the comment. When I'm console.log(post.comments) it shows me all the comments but still, I can't find the comment. The error was Comment not found which I wrote to find that comment is still there or not. But the comment was there I matched the id with it. Help me I'm new to NodeJs. Help me to fix this

*As a frontend I'm using react and redux I think the problem is in the backend, I've also tested with the postman. Can't delete the comment from postman.

here is the comment route and controller

router.route('/:id/comment/:comment_id').delete(protect, deleteComment);

export const deleteComment = asyncHandler(async (req, res) => {
  const post = await Post.findById(req.params.id);

  const comment = post.comments.find(
    (comment) => comment._id === req.params.comment_id
  );

  if (!comment) {
    res.status(404);
    throw new Error('Comment not found');
  }

  //Check User

  if (comment.user.toString() === req.user._id.toString()) {
    post.comments = post.comments.filter(
      ({ id }) => id !== req.params.comment_id
    );

    await post.save();

    return res.json(post.comments);
  } else {
    res.status(401);
    throw new Error('User not authorized');
  }
});

here is the post model

import mongoose from 'mongoose';

const postSchema = mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: [true, 'Please Author is required'],
    },
    title: {
      type: String,
      required: true,
    },
    desc: {
      type: String,
      required: true,
    },
    img: {
      type: String,
    },
    isLiked: {
      type: Boolean,
      default: false,
    },
    isDisLiked: {
      type: Boolean,
      default: false,
    },
    likes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
      },
    ],
    disLikes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
      },
    ],
    comments: [
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        text: {
          type: String,
          required: true,
        },
        name: {
          type: String,
        },
        pic: {
          type: String,
        },
        date: {
          type: Date,
          default: Date.now,
        },
      },
    ],
    categories: {
      type: Array,
    },
  },
  {
    timestamps: { createdAt: 'created_at', updatedAt: 'modified_at' },
  }
);

const Post = mongoose.model('Post', postSchema);

export default Post;

Solution

  • When you access to the _id you are accessing the instance of the ObjectId

    You should try to compare with the id, that is a string representation of the _id

    const comment = post.comments.find(
        (comment) => comment.id === req.params.comment_id
      );