mongoose CastError:对于模型的路径“_id”处的值“test33”(类型字符串),强制转换为ObjectId失败

k5ifujac  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(219)

我正在自学网页开发,通过参加Colt Steele的udemy课程,我撞到了墙上..我不知道为什么它在下面的代码中显示转换为ObjectId错误..我试图调试它,但无法找到这个错误消息的原因.我发现的唯一一件事是,当我通过输入/更新图像URL到纯文本没有“http://"创建/编辑数据时,它显示这个错误消息.请帮助我..我在这里困了几天,仍然不明白..
错误信息

  1. const castError = new CastError();
  2. ^
  3. CastError: Cast to ObjectId failed for value "test33" (type string) at path "_id" for model "Yelpcamp"
  4. at model.Query.exec (/Users/doriyomi/Web Development/YELPCAMP/node_modules/mongoose/lib/query.js:4498:21)
  5. at model.Query.Query.then (/Users/doriyomi/Web Development/YELPCAMP/node_modules/mongoose/lib/query.js:4592:15)
  6. at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  7. messageFormat: undefined,
  8. stringValue: '"test33"',
  9. kind: 'ObjectId',
  10. value: 'test33',
  11. path: '_id',
  12. reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

app.js

  1. const express = require('express');
  2. const app = express();
  3. const path = require('path');
  4. const mongoose = require('mongoose');
  5. const CampGround = require('./models/main');
  6. const methodOverride = require('method-override');
  7. const engine = require('ejs-mate');
  8. const db = mongoose.connect('mongodb://localhost:27017/yelpcamp', {
  9. useNewUrlParser: true,
  10. useUnifiedTopology: true
  11. });
  12. db.then(()=> {
  13. console.log('connected to Mongo DB!');
  14. })
  15. //to use req.body. it must be needed.
  16. app.use(express.urlencoded({ extended: true }));
  17. app.use(methodOverride('_method'));
  18. app.engine('ejs', engine); //connect ejs-mate to ejs, then boilerplate layout can be used.
  19. app.set('view engine', 'ejs');
  20. app.set('views', path.join(__dirname,'views'));
  21. app.get('/main', async (req, res)=> {
  22. console.log("Basic route opened!!");
  23. const allData = await CampGround.find({});
  24. res.render('campground/main', {allData});
  25. })
  26. app.post('/main', async (req, res) => {
  27. console.log('New -> save() function opened');
  28. console.log(`title: ${req.body.campground.title}`);
  29. console.log(`image: ${req.body.campground.image}`);
  30. console.log(`location: ${req.body.campground.location}`);
  31. console.log(`price: ${req.body.campground.price}`);
  32. const newData = new CampGround(req.body.campground);
  33. await newData.save();
  34. res.redirect('/main');
  35. })
  36. app.get('/main/new', (req, res) => {
  37. // console.log('new page works in express');
  38. res.render('campground/new');
  39. })
  40. app.get('/main/:id', async (req, res) => {
  41. // console.log('id page works');
  42. const {id} = req.params;
  43. const foundData = await CampGround.findById(id);
  44. res.render('campground/showbyid',{foundData});
  45. })
  46. app.put('/main/:id', async(req, res) => {
  47. // const {title, location} = req.body;
  48. // console.log(req.body.campground);
  49. await CampGround.findByIdAndUpdate(req.params.id,{...req.body.campground}, {new: true, useFindAndModify: false});
  50. res.redirect(`/main/${req.params.id}`);
  51. })
  52. app.get('/main/:id/edit', async(req, res) => {
  53. const {id} = req.params;
  54. const foundData = await CampGround.findById(id);
  55. console.log(foundData);
  56. res.render('campground/edit', {foundData});
  57. })
  58. app.delete('/main/:id', async(req, res) => {
  59. await CampGround.findByIdAndDelete(req.params.id, {useFindAndModify: false});
  60. res.redirect('/main');
  61. })
  62. app.listen(3000, ()=> {
  63. console.log("Port open!!");
  64. })

main.ejs //显示所有列表

  1. <% layout('./layout/boilerplate') %>
  2. <div class="container mt-5 mb-5">
  3. <h1>Campgrounds!!</h1>
  4. <% for(let a of allData.reverse()) { %>
  5. <div class="card w-75">
  6. <div class="row">
  7. <div class="col-md-5">
  8. <img src="<%=a.image%>" class="img-fluid img-thumbnail">
  9. </div>
  10. <div class="col-md-7">
  11. <div class="card-body">
  12. <h5 class="card-title">
  13. <%=a.title%>
  14. </h5>
  15. <h6 class="card-subtitle mb-2 text-muted">
  16. <%=a.location%>
  17. </h6>
  18. <p class="card-text">
  19. <%=a.description%><br><br>
  20. <a href="/main/<%=a._id%>" class="btn btn-primary">Detail</a>
  21. </p>
  22. </div>
  23. </div>
  24. </div>
  25. </div>
  26. <% } %>
  27. </div>

new.ejs //列表创建部分

  1. <% layout('./layout/boilerplate') %>
  2. <div class="row mt-5">
  3. <h1 class="text-center">New Data Creation</h1>
  4. <div class="col-md-6 offset-3">
  5. <form action="/main" method="POST">
  6. <div class="mb-3">
  7. <label class="form-label" for="titleid">Title: </label>
  8. <input class="form-control" type="text" id="titleid" name="campground[title]" placeholder="Title here">
  9. </div>
  10. <div class="mb-3">
  11. <label class="form-label" for="locationid">Location: </label>
  12. <input class="form-control" type="text" id="locationid" name="campground[location]" placeholder="Location here">
  13. </div>
  14. <label class="form-label" for="imgurlid">URL </label>
  15. <div class="input-group mb-3">
  16. <span class="input-group-text">@</span>
  17. <input type="text" class="form-control" placeholder="IMG URL here" id=imgurlid name="campground[image]">
  18. </div>
  19. <label class="form-label" for="priceid">Price </label>
  20. <div class="input-group mb-3">
  21. <span class="input-group-text">$</span>
  22. <input type="text" class="form-control" placeholder="Price here" id=priceid name="campground[price]">
  23. </div>
  24. <div class="mb-3">
  25. <label class="form-label" for="descid">Description: </label>
  26. <textarea class="form-control" type="text" id="descid" name="campground[description]" placeholder="Description here"></textarea>
  27. </div>
  28. <div class="mb-3">
  29. <button class="btn btn-success" >create</button>
  30. </div>
  31. <a href="/main/">Back to main</a>
  32. </form>
  33. </div>
  34. </div>
44u64gxh

44u64gxh1#

我遇到了这个错误,我通过修改以下行解决了它。
举个例子:

  1. app.get('/main/:id', async (req, res) => {
  2. // console.log('id page works');
  3. const {id} = req.params;
  4. const foundData = await CampGround.findById(id);
  5. res.render('campground/showbyid',{foundData});
  6. });

在我的代码中,它将是:

  1. app.get('/main/:id', async (req, res) => {
  2. // console.log('id page works');
  3. const id = req.params.id;
  4. const foundData = await CampGround.findOne({_id: id});
  5. res.render('campground/showbyid',{foundData});
  6. });

我希望能帮上忙,至少让你尝试另一种选择。

展开查看全部

相关问题