0
votes

I am creating a program to perform CRUD operations and I am getting an error:

Cast to ObjectId failed for value \":5e1360c5edb2922570aa2611\" at path \"_id\" for model \"colt\"",

Here is my code:

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

Here is the show edit ejs file:

<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>

And this is my mongoose schema:

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

let colt = mongoose.model("colt", coltSchema);
1
Convert _id into mongoose ObjectId var mongoose = require('mongoose'); var _id = mongoose.Types.ObjectId(_id); - jitendra kumar

1 Answers

0
votes

You don't have to write : in your link when using url params

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

Due to this, the value your route gets in ids is :5e1360c5edb2922570aa2611 instead of 5e1360c5edb2922570aa2611 only

Remove the : from url of form action & you're good to go