【问题标题】:Cast to ObjectId failed for value \":5e1360c5edb2922570aa2611\" at path \"_id\" for model \"colt\"" error对于模型 \"colt\"" 错误的路径 \"_id\" 中的值 \":5e1360c5edb2922570aa2611\" 转换为 ObjectId 失败
【发布时间】:2020-04-24 15:50:57
【问题描述】:

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

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

这是我的代码:

// 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);

【问题讨论】:

  • 将_id转换为mongoose ObjectId var mongoose = require('mongoose'); var _id = mongoose.Types.ObjectId(_id);

标签: javascript node.js mongodb mongoose


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2019-06-26
    • 1970-01-01
    • 2020-05-11
    • 2019-10-10
    • 2020-10-19
    • 2023-03-28
    • 2018-07-10
    • 2017-05-23
    相关资源
    最近更新 更多