{ "_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 });
}
};
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](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 });
}
});
注意:无法使用猫鼬访问对象的属性。我能够通过 http:localhost:3000/api/site 获得响应,但不能通过 http:localhost:3000/main 获得响应。相反,我收到此错误: {“错误”:“无法读取未定义的属性(读取'状态')”}
我不确定我的答案,因为我无法运行代码。 但正如我所看到的,您已经在
getAllSites
控制器内响应了即将到来的请求。
一旦您发送了 response
,请求-响应周期就会关闭,因此这行代码:
const sites = await siteController.getAllSites();
未获得预期并等待的
sites
值,因为 getAllSites
确实关闭了请求-响应周期,它不返回任何值。
我认为你应该重新组织你的代码。 我看不出仅仅为了执行此行而创建整个控制器有任何意义:
const sites = await Site.find();
你可以考虑这样做:(在我看来,它更干净)
router.get('/', getAllSites);
然后将所有代码移至
getAllSites
内部,最后,像您一样从那里发送响应。
或者将你的控制器修改为这样:
const getAllSites = async (req, _, next) => {
try {
const sites = await Site.find();
req.sites = sites; // this is going to include the data to the current request so the next middleware in the stack can access it.
next();
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.get('/', getAllSites, async (req, res) =\> {
try {
const sites = req.sites;
if (sites && Array.isArray(sites)) {
res.render('main', {
profile_picture_url: '[https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing](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 });
}
});
希望我的回答可以对您和其他人有所帮助