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