node.js - 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
})
})
解决方案
如果你遇到的和我之前遇到的一样……这是你的路由代码顺序造成的。确保在您放置的路线上使用参数时
// Company Route
router.get('/list/:id', getCompanyData, (req, res) => {
// console.log(req.companyData.name);
res.render('company', {
company: req.companyData
})
})
一直到代码的底部...因为假设您有另一条路线/list/profile...它会给您该错误,因为profile不是objectId。
推荐阅读
- javascript - Ajax Call 移除 UI 元素
- antlr4 - 如何根据ANTLR4中的关键字跳过输入
- python - 使用 Python Scrapy 无法抓取 BBC
- javascript - 将 .mp3 转换为 .ogg 作品/电报机器人/节点 js
- git - 如何将 10GB 的文件推送到 git?
- google-apps-script - 将日期从 d"-"mmm"-"yy 格式化为 "YYYY-MM-DD" 输出无效年份
- node.js - 部署 ReactJs + MySQL + NodeJs Express 项目
- python - pytest:在测试用例不可见的夹具中分配属性
- sql - SQL : 获取对应数据的 SQL 查询
- python - 将 Pandas 数据框导出到 Excel 时为特定单词着色