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
- Authenticate.
- Send:
POST /api/comments
Content-Type: application/json
Authorization: Bearer <token>
{
"contentType": "invalid",
"contentId": "507f1f77bcf86cd799439011",
"content": "orphan comment"
}
- 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.
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.jssaves immediately:Parent lookup happens only after saving, and invalid
contentTypehas no rejection path.Reproduction
{ "contentType": "invalid", "contentId": "507f1f77bcf86cd799439011", "content": "orphan comment" }Expected
Invalid
contentTypeshould 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.