无法推送评论对象至数组:博客评论提交失败及Mongoose验证错误
解决评论提交失败的ValidationError问题
嘿,我看你在提交评论到营地页面评论区时遇到了ValidationError,错误提示说Cast to [undefined] failed,这问题我熟,咱们一步步来解决:
问题根源
先看你的Campground Schema定义:
var campgroundSchema=new mongoose.Schema({ name: String, image: String, desc:String, comments: [ { type :mongoose.Schema.Types.ObjectId , ref:"Comment" } ] });
这里comments数组明确要求存储Comment文档的ObjectId,但你在POST路由里是这么写的:
campground.comments.push(comment); campground.save();
你把Comment.create返回的完整comment文档对象直接push进去了,而不是取它的_id字段。mongoose尝试把整个comment对象转换成ObjectId时自然会失败,所以抛出了类型转换的验证错误。
修复方案
只需要修改push的内容,把完整的comment对象换成它的_id就行;另外最好给campground.save()加上回调,确保保存完成后再跳转(避免异步操作带来的潜在问题):
修改后的POST路由代码:
app.post("/campgrounds/:id/comments", function(req,res){ // 查找对应营地 Campground.findById(req.params.id, function(err,campground){ if(err){ console.log(err); res.redirect("/campgrounds"); }else{ Comment.create(req.body.comment, function(err,comment){ if(err){ console.log(err); }else{ // 只push评论的ObjectId campground.comments.push(comment._id); // 加上回调确保保存完成后再跳转 campground.save(function(err){ if(err){ console.log(err); }else{ res.redirect("/campgrounds/" + campground._id); } }); } }); } }); });
额外说明
这样修改后,mongoose就能正确把Comment的ObjectId存入campground的comments数组里,和你的Schema定义完全匹配,验证错误就会消失啦。另外加上save的回调也更严谨,能处理保存过程中可能出现的意外错误。
内容的提问来源于stack exchange,提问作者shaykoo
相关产品推荐
相关产品推荐

