首页 > 解决方案 > CastError:模型“Company”的路径“_id”处的值“...”转换为 ObjectId 失败

问题描述

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

错误

中间件文件:

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
  })
})

标签: node.jsmongodbmongoose

解决方案


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

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

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


推荐阅读