0
votes

When attempting to use req.params.id inside my delete (or update for that matter) route I am getting the above message. This has stumpted me for some time and I'm sure I'm making a mistake somewhere with my routes / objects.

Changing the app from res.render("/campgrounds/ + req.params.id); to - res.render("/campgrounds"); solves the issue but doesn't reload the same page like i'm look to have it do. I can't wrap my head around why the app is returning undefined when accessing the campground route from req.params.id.

var express= require("express");
var router = express.Router();
var Comment = require("../models/comment");
var Campground = require("../models/campgrounds");


// COMMENTS EDIT ROUTE



router.get("/campgrounds/:id/comments/:comment_id/edit", function(req, res){

            Comment.findById(req.params.comment_id, function(err, foundComment){
                if(err){
                    console.log(err)
                } else {
                    res.render("comments/edit", {campground_id: req.params.id, comment: foundComment})
                }
            })
        })


// comment update 

//campgrounds/:id/comments/:comment_id
router.put("/:comment_id", function(req, res){
    Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err, updatedComment){
        if(err){
            console.log(err)
        } else {
            // KNOWN BUG - /campgrounds/ + req.params.id will return cast to boject failed for value undefined at path _id. having the app redirect to all campgrounds page as a work around
            res.redirect("/campgrounds");
        }
    })
})

// DELETE ROUTER
router.delete("/:comment_id", function(req, res){
    Comment.findByIdAndRemove(req.params.comment_id, function(err){
        if(err){
            res.redirect("back");
        } else {

            res.redirect("/campgrounds/" + req.params.id);
        }
    })
})



function isLoggedIn(req, res, next){
    if(req.isAuthenticated()){
     return next();   
    } else {
        res.redirect("/login");
    }
}

module.exports = router;
5
can you give me the request url how are you accessing the url from server@AndyVignesh
app.listen(process.env.PORT, process.env.IP, function(){ console.log("App is running"); }) <-- is this what you're looking for? @VigneshAndy

5 Answers

2
votes

I've ran into the same issue, and it was due to route order. I moved the show route below the index route cuz "it flows better", but that broke the code, and confused it since I think route order matters. make sure your route make sense from the applications point of view if you reordered them

0
votes

Make sure you have input field name "id" in comment form (or "id" in ajax request).

router.put("/:comment_id", function(req, res){
    const id = req.params.id;
    console.log(id);
    Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err, updatedComment){
        if(err){
            console.log(err)
        } else {
            res.redirect("/campgrounds/" + id);
        }
  })
})
0
votes

I think your problem is you are not sending the comment_id from html to controller try printing the req.params.comnent_id

then try this

    var express= require("express");
    var router = express.Router();
    var Comment = require("../models/comment");
    var Campground = require("../models/campgrounds");


    // COMMENTS EDIT ROUTE



    router.get("/campgrounds/:id/comments/:comment_id/edit", function(req, res){
    console.log("params.comment_id",params.comment_id);
   if(req.params.comment_id){
      Comment.findById(req.params.comment_id, function(err, foundComment){
                    if(err){
                        console.log(err)
                    } else {
                        res.render("comments/edit", {campground_id: req.params.id, comment: foundComment})
                    }
              }else {
                        res.render("comments/edit", {campground_id: req.params.id, comment: foundComment})
                    }

                })
            })
0
votes

Ok guys, I recently encountered the same problem. I tried finding solutions all over the internet but failed to get any useful answers.

Then I tried looking hard into the "CastError" and found that the ID I am getting from 'req.params.id' had an extra white space in front of it.

For example: instead of '5bed4f6276c4920db404eb25', I got ' 5bed4f6276c4920db404eb25' as the ID. I don't know (yet) why I get the id with that extra white space but I figured that white space must be the issue.

So I stripped the ID for white space with javascript replace function as follows:

    var curid = req.params.id;
    curid = curid.replace(/\s/g,'');

and it worked!

So instead of

    Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err, updatedCamp){..}

now use:

    Campground.findByIdAndUpdate(curid, req.body.campground, function(err, updatedCamp){..}

So,you have to replace all

    req.params.id

in your code block with

    curid

And you are good to go!

Here is the whole code block for your reference:

router.put("/:id", function(req, res){
var curid = req.params.id;
curid = curid.replace(/\s/g,'');

Campground.findByIdAndUpdate(curid, req.body.campground, function(err, updatedCamp){
    if(err){
        console.log(err);
        res.redirect("/campgrounds");
    } else{
        //redirect somewhere (show page)
        res.redirect("/campgrounds/" + curid);        
    }
});
0
votes

The best solution to this problem is reformat the _id by cleaning the blank space it added (in my case coming from a form in my template "x.ejs")

const to_remove = req.body.checkbox;//id from template is wrong
const listname = req.body.check_list_name;

let **to_rem_cured** = to_remove.replace(/\s/g,'');

List.findOneAndUpdate({name:listname},{'$pull':{list:{_id: **to_rem_cured**  }}},function(err,doc){
  if(!err){
    console.log(doc);

    res.redirect("/"+listname);
  }
  else{
    console.log(err);

  }
});