【问题标题】:errorCastError: Cast to ObjectId failed for value "comment" at path "comments"errorCastError:路径“comments”处的值“comment”转换为 ObjectId 失败
【发布时间】:2019-12-24 17:34:55
【问题描述】:

当我提交表单时,我不断收到以下信息:

errorCastError: 路径中值“comment”的转换为 ObjectId 失败 "cmets"

我希望你的问题是正确的

这是req的形式

action="/campground/<%= camp._id %>/comments/" method="POST">

这是渲染表单页面的路径

app.get("/campground/:id/comments/new", function(req, res){
    Campground.findById(req.params.id, function(err, camp){
        if(err){
            console.log(err);
        } else {
            res.render("comments/new", {camp: camp});
        }
    });    
});

这是创建评论并将其与露营地相关联的发布路线

app.post("/campground/:id/comments", function(req, res){
   Campground.findById(req.params.id, function(err, camp){
      if(err){
          console.log(err);
          res.redirect("/");
      } else {
          Comment.create(req.body.comment, function(err, comment){
              if(err){
                  console.log(err);
              } else {
                 camp.comments.push("comment");
                 camp.save();
                 res.redirect("/campground/" + req.params.id);
              }
          });
      }
   }); 
});

应用正在监听这个

app.listen(process.env.PORT, process.env.IP);

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    您正在推送一个 "comment" 的字符串,同时需要对象或仅 id,以下示例可能对您有所帮助

    camp.comments.push(comment);
    

    camp.comments.push(comment._id);
    

    而不是camp.comments.push("comment");

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 1970-01-01
      • 2014-06-20
      • 2017-05-19
      • 2017-11-10
      • 2019-10-10
      • 2016-11-11
      • 2017-03-26
      • 2017-05-26
      相关资源
      最近更新 更多