使用Mongoose遇错:/main路由返回Cannot read properties of undefined错误
问题描述
通过http://localhost:3000/api/site可正常获取响应,但访问http://localhost:3000/main时出现错误:
{"error":"Cannot read properties of undefined (reading 'status')"}
示例数据
{ "_id": "ObjectId_for_Site1", "name": "Site 1", "address": "123 Reeganangam", "manager": { "_id": "ObjectId_for_Manager1", "name": "Karthik", "type": "Manager" } }
控制器代码
const getAllSites = async (req, res) => { try { const sites = await Site.find(); console.log(sites); res.status(200).json(sites); } catch (error) { res.status(500).json({ error: error.message }); } };
Schema定义
const managerSchema = new Schema({ _id: mongoose.Schema.Types.ObjectId, name: String, type: String, }); const siteSchema = new Schema({ _id: mongoose.Schema.Types.ObjectId, name: String, address: String, manager: managerSchema, }); const Site = mongoose.model('Site', siteSchema, 'Site_Collection');
控制器引用位置
router.get('/', async (req, res) => { try { const sites = await siteController.getAllSites(); if (sites && Array.isArray(sites)) { const siteNames = sites.map((site) => site.name); res.render('main', { profile_picture_url: 'https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing', username: 'Sundar', sites: siteNames, }); } else { res.status(500).json({ error: 'Failed to fetch sites data' }); } } catch (error) { res.status(500).json({ error: error.message }); } });
问题原因与修复方案
核心原因
getAllSites函数原本为API路由设计,依赖传入的req和res对象返回响应。但在main路由调用时未传递任何参数,导致函数内部res为undefined,执行res.status()时触发错误。同时该函数仅直接返回JSON响应,不会将查询结果返回给调用方,导致main路由中sites变量始终为undefined,后续逻辑无法正常执行。
修复方法
重构getAllSites,让它仅负责数据查询,将响应处理交给调用方,实现逻辑复用:
1. 修改控制器中的getAllSites函数
// 仅负责查询数据,不处理响应 const getAllSites = async () => { try { const sites = await Site.find(); console.log(sites); return sites; // 返回查询结果 } catch (error) { throw error; // 抛出错误,由调用方处理 } };
2. 调整API路由的调用逻辑
若原API路由直接使用getAllSites,需改为:
router.get('/api/site', async (req, res) => { try { const sites = await siteController.getAllSites(); res.status(200).json(sites); } catch (error) { res.status(500).json({ error: error.message }); } });
3. main路由逻辑无需额外修改
修改后的getAllSites会返回查询到的站点数组,main路由可正常获取数据并渲染页面。
内容的提问来源于stack exchange,提问作者Ashok Kumar Maharajan
相关产品推荐
相关产品推荐

