0
votes

Hey guys could really use some help with a DELETE route. I'm working with RESTful routing, trying to follow the conventions and when adding the delete route I get the error:

CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"

I've searched for the issue on stackoverflow and the best I could come up with was the version of mongoose had a bug. I rolled it back to V 4.10.0 and am still getting the issue. My code follows:

var express    = require("express"),
app        = express(),
bodyParser = require("body-parser"),
mongoose   = require("mongoose"),
methodOverride = require("method-override");


           // APP CONFIG
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

mongoose.connect("mongodb://localhost/restful_blog_app");

// Create a new Blog Schema defines what the object will be

var Blog = new mongoose.Schema ({
    title: String,
    image: String, //{type: String, default: "placeholder.jpg"} for a default image
    body: String,
    created: {type: Date, default: Date.now}
});

// Mongoose compiles the Schema into a model, useable object
var Blog = mongoose.model("Blog", Blog);


// DELETE ROUTE 

app.delete("/blogs/:id", function(req, res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if(err){
            console.log(err)
        }

    })
})
2
Found the error, it was in my ejs file. I noticed that the error message had a space between the first quotation and the actual id itself so " 92384759" rather than "92384759". I removed the space and it works perfectly. The second fault on my part is for editing the error message in my original question (I should have just copied and pasted the objectid rather than abbreviate with " X").Andy

2 Answers

0
votes

I think the id parameter that you get is not a valid ObjectId string, so it can't be casted to a ObjectId Object.

Here you have have some information about ObjectId, check you are passing a valid one.

0
votes

Found the error, it was in my ejs file. I noticed that the error message had a space between the first quotation and the actual id itself so " 92384759" rather than "92384759". I removed the space and it works perfectly. The second fault on my part is for editing the error message in my original question (I should have just copied and pasted the objectid rather than abbreviate with " X"). – Andy 9 hours ago