【发布时间】:2021-07-11 23:52:02
【问题描述】:
我正在尝试到达某个路线,其中包含一个表单,但由于某种原因它正在寻找一个 id。我将分享我的路线、我的观点和错误。
//celebrities routes
const express = require('express');
const router = express.Router();
const Celeb = require('../model/celebrity.model')
router.get('/celebrities', (req, res) => {
Celeb.find()
.then(AlltheModels => {
console.log(AlltheModels)
res.render('celebrities/index', { celebs: AlltheModels })
})
.catch(error => console.log('error while getting the celebrities', error))
})
router.get('/celebrities/:id', (req, res) => {
const celebId = req.params.id
console.log(celebId)
Celeb.findById(celebId)
.then(OneCeleb => {
console.log(OneCeleb)
res.render('celebrities/show', { celebOne: OneCeleb })
})
.catch(error => console.log('there was an error by retrieving..', error))
})
//NEW celebrities
router.get('/celebrities/new', (req, res) => {
res.render('celebrities/new')
})
router.post('/celebrities', (req, res) => {
const { name, occupation, catchPhrase } = req.body;
Celeb.create({ name, occupation, catchPhrase })
// .then(CelebNew => {
// CelebNew.save()
// console.log(CelebNew + '...has been entered')
// })
.then(() => res.redirect('/celebrities'))
.catch(error => `There was an error of ${error}`, err)
})
module.exports = router;
这是应该指向表单视图的视图
<div>
<a href="/celebrities/new">Create a new Celebrity</a>
</div>
<div>
{{#each celebs}}
<a href="/celebrities/{{_id}}">
<h2>{{this.name}}</h2>
</a>
{{/each}}
</div>
这是错误
"GET /celebrities/new - - ms - -
...检索出错.. CastError: Cast to ObjectId failed for value "new" at path "_id" for model "Celeb" 在 model.Query.exec (/mnt/c/Users/carlo/documents/ironhack/labs/lab-mongoose-movies/starter-code/node_modules/mongoose/lib/query.js:4408:21)"
据我了解,问题出在这条路线上
router.get('/celebrities/:id', (req, res) => {
const celebId = req.params.id
console.log(celebId)
Celeb.findById(celebId)
.then(OneCeleb => {
console.log(OneCeleb)
res.render('celebrities/show', { OneCeleb })
})
.catch(error => console.log('there was an error by retrieving..', error))
})
但我不知道错误的原因或位置,或者为什么它试图寻找新的 Id,是车把助手吗?。
【问题讨论】:
-
而不是 URL 末尾的“/new”,而是“/0”。路由参数 ID 始终应为数字。我不确定这是否与 Celeb.findById 混淆,但您只需要返回一个新实例
标签: javascript node.js express routes handlebars.js