gpt4 book ai didi

javascript - [ Actor 错误: Cast to ObjectId failed for value "undefined" at path "_id"

转载 作者:行者123 更新时间:2023-12-01 02:58:22 25 4
gpt4 key购买 nike

当尝试在我的删除(或更新)路由中使用 req.params.id 时,我收到上述消息。这困扰了我一段时间,我确信我在路线/对象的某个地方犯了错误。

将应用程序从 res.render("/campgrounds/+ req.params.id); 更改为 - res.render(“/露营地”);解决了问题,但没有像我希望的那样重新加载同一页面。我无法理解为什么当从 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;

最佳答案

我遇到了同样的问题,这是由于路线顺序造成的。我将显示路线移至索引路线下方,因为“它流动得更好”,但这破坏了代码,并且混淆了它,因为我认为路线顺序很重要。如果您重新排序,请确保您的路线从应用程序的 Angular 来看是有意义的

关于javascript - [ Actor 错误: Cast to ObjectId failed for value "undefined" at path "_id",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46597923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com