首页 > 解决方案 > 对于模型 \"colt\"" 错误的路径 \"_id\" 处的值 \":5e1360c5edb2922570aa2611\" 转换为 ObjectId 失败

问题描述

我正在创建一个程序来执行 CRUD 操作,但出现错误:

对于模型 \"colt\"" 的路径 \"_id\" 处的值 \":5e1360c5edb2922570aa2611\",转换为 ObjectId 失败,

这是我的代码:

// here is the route of edit path
app.get("/edit/:ids", (req, res) => {
  colt.findById(req.params.ids, (err, coltz) => {
    if (err) {
      res.redirect("/");
    } else {
      res.render("showedit", { colt: coltz });
    }
  });
});

// here is the update route
app.put("/edit/:ids", (req, res) => {
  colt.findByIdAndUpdate(req.params.ids, req.body.colts, err => {
    if (err) {
      res.send(err);
    } else {
      res.redirect("/show");
    }
  });
});

这是显示编辑 ejs 文件:

<h1>HELLO HERE YOU CAN UPDATE</h1>
<form action="/edit/:<%=colt._id%>?_method=PUT" method="POST">
    <input type="text" placeholder="name here" name="colts[name]" value="<%= colt.name  %>">

    <input type="text" placeholder="description here" name="colts[description]" value="<%= colt.description  %>">

    <input type="text" placeholder="img url here" name="colts[url]" value="<%= colt.url  %>">
    <input type="submit">
</form>

这是我的猫鼬模式:

var coltSchema = new mongoose.Schema({
  name: String,
  description: String,
  url: String
});

let colt = mongoose.model("colt", coltSchema);

标签: javascriptnode.jsmongodbmongoose

解决方案


使用 url 参数时,您不必在链接中写:

<form action="/edit/:<%=colt._id%>?_method=PUT" method="POST"> // remove : from this line

因此,您的路线在 ids 中获得的:5e1360c5edb2922570aa26115e1360c5edb2922570aa2611不仅仅是

从表单操作的 url 中删除 : 就可以了


推荐阅读