ValidationError: comment validation failed: commentId: Cast to Number failed for value "NaN" (type number) at path "commentId"
//post마다 commentId가 1부터 시작하게 만들고싶은거임
//post경우에는 null이였는데, 여기선 post가 존재할 때도 더해주는 거니까. NaN + 1 === NaN
!! 그때그때 다르게한다. DB를 2번 들리는방법, 저장할때 필요한 변수도 같이 넣는방법.
//생성
router.post('/posts/:postId/comments', authMiddleware, async (req, res) => {
const { userId, nickname } = res.locals.user;
const { postId } = req.params;
const { comment } = req.body;
const maxBycommentId = await Posts.findOne({ postId }).sort("-commentId").exec();
const commentId = maxBycommentId ? maxBycommentId.commentId + 1 : 1;
if (!comment) {
return res.json({ errormessage: "데이터 형식이 올바르지 않습니다." });
};
await Comments.create({
commentId,
postId,
userId,
nickname,
comment
});
return res.json({ "message": "댓글을 생성하였습니다." });
});
const mongoose = require("mongoose");
const commentSchema = new mongoose.Schema({
commentId: {
type: Number,
required: true,
},
nickname: { // nickname 필드
type: String,
required: true,
},
userId: {
type: Number,
required: true,
},
comment: {
type: String,
required: true
},
},
{ timestamps: true }
);
module.exports = mongoose.model("comment", commentSchema);