Skip to content

Comment API creates orphan comments for invalid or missing parent content #72

Description

@vipul674

Bug

The comment API can create orphan comments because it saves the comment before validating that the parent question/answer exists.

Evidence

server/routes/comments.js saves immediately:

const comment = new Comment({ author: req.user._id, contentType, contentId, content });
await comment.save();

Parent lookup happens only after saving, and invalid contentType has no rejection path.

Reproduction

  1. Authenticate.
  2. Send:
POST /api/comments
Content-Type: application/json
Authorization: Bearer <token>
{
  "contentType": "invalid",
  "contentId": "507f1f77bcf86cd799439011",
  "content": "orphan comment"
}
  1. The API returns 201 and stores a comment that is not attached to a valid parent.

Expected

Invalid contentType should return 400. Missing parent question/answer should return 404 before saving.

Actual

The comment is saved before parent validation.

Suggested fix

Validate contentType, fetch the parent first, and only save the comment after parent existence is confirmed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions