0
var blogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {type: Date, default: Date.now}
});

app.put("/blogs/:id",function(req,res){
Blog.findByIdAndUpdate(req.params.id, req.body.blog ,function(err,updateBlog){
    if(err){
        console.log(err);
        console.log(req.body.blog._id);
        console.log(req.body.blog.title);
        console.log(req.body.blog.image);
        console.log(req.body.blog.body);
    }
    else{
        res.redirect("/blogs/" + req.params.id);
    }
});

I have skipped the unnecessary code. The error I received as been pasted below. Just need help to figure out why my blog._id isn't working properly, the rest title, image, body are working properly. Console.log is printing blog._id as undefined. Any help will be appreciated. Thanks.

{ CastError: Cast to ObjectId failed for value " 5ae8264a3812d31e7ac0c7c2" at path "_id" for model "Blog"

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Dhruv Nunia
  • 37
  • 10
  • Please don't post images and just include the text instead. But your "image" clearly shows a **leading space** in front of the string value for the id. Trim the leading space to correct the error. – Neil Lunn May 06 '18 at 08:29
  • I have not declared id value in my entire code. I am just importing it through req.params.id and blog._id from mongodb database directly. I am kind of a beginner. Can you please be more specific please. – Dhruv Nunia May 06 '18 at 08:40
  • 1
    The `req.params.id` value has a "space" at the beginning. Clean it up with `req.params.id = req.params.id.trim();` before sending into the mongoose method. You probably really should be looking at the code that is sending the request, because the space really should not be there. But it's good to sanitize at any rate. Sort of surprised that mongoose is not doing this. – Neil Lunn May 06 '18 at 08:45
  • Thanks a lot it worked. The tutorial I was following didn't need .trim() so was stuck there. – Dhruv Nunia May 06 '18 at 08:51
  • Possible duplicate of [How update the \_id of one MongoDB Document?](https://stackoverflow.com/questions/4012855/how-update-the-id-of-one-mongodb-document) – Ivan Beldad May 06 '18 at 08:54
  • @IvandelaBeldad No it's not a duplicate of that. The OP isn't trying to actually "update" the `_id` field of the document despite the question title. Their issue is on "upsert" and a "cast error" due to leading whitespace. I nearly marked that myself until I looked at the screenshot in the question. – Neil Lunn May 06 '18 at 08:57
  • 1
    As stated, you should not "need" the trim. My guess here is whatever tutorial you are following has you clicking on a link in client html. The problem is that in the generation of this link you have a "leading space". So this is probably from your own template code, and you will have that error there. – Neil Lunn May 06 '18 at 08:59
  • Thanks . Will look into it too. – Dhruv Nunia May 06 '18 at 09:03

0 Answers0