【问题标题】:CastError: Cast to ObjectId failed for value "..." at path "_id" for model "Company"CastError:模型“Company”的路径“_id”处的值“...”转换为 ObjectId 失败
【发布时间】:2020-11-19 17:47:45
【问题描述】:

我正在为项目使用示例 MongoDB 数据库,在使用 findById mongoose 方法时,我收到错误:'CastError: Cast to ObjectId failed for value "..." at path "_id" for model "Company" '。我使用车把作为视图引擎。

error

中间件文件:

getCompanyData: async (req, res, next) => {
    // Queries
    const information =
      "name ipo founded_day founded_month founded_year description overview relationships";
    // try {
      const getCompanyData = await Companies.findById(req.params.id, information).exec();
      console.log(getCompanyData);
      // Coverting Mongoose Document to Object
      const companyData = getCompanyData.toObject()
      // console.log(companyData); 

这是路由文件

// Company Route
router.get('/list/:id', getCompanyData, (req, res) => {
  // console.log(req.companyData.name);
  res.render('company', {
    comapany: req.companyData
  })
})

【问题讨论】:

  • 你为什么要在 findById() 中传递变量information,我认为你不能这样做。顺便说一句,你想达到什么目的?
  • 他正在尝试使用第二个参数作为字符串从结果中获取一些选择性字段。
  • 请 console.log(req.params.id) 并尝试将其类型转换为对象 ID。 id = mongoose.Types.ObjectId(req.params.id)

标签: node.js mongodb mongoose


【解决方案1】:

如果你遇到的和我之前遇到的一样……这是你的路由代码顺序造成的。确保在您放置的路线上使用参数时

// Company Route
router.get('/list/:id', getCompanyData, (req, res) => {
  // console.log(req.companyData.name);
  res.render('company', {
    company: req.companyData
  })
})

一直到代码的底部...因为假设您有另一个路由 /list/profile...它会给您该错误,因为 profile 不是 objectId。

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 2021-07-04
    • 2017-08-18
    • 2016-11-11
    • 2017-03-26
    • 2017-05-26
    • 2020-05-20
    • 2020-12-10
    • 2021-02-21
    相关资源
    最近更新 更多