Sample data:
{ "_id": "ObjectId_for_Site1", "name": "Site 1", "address": "123 Reeganangam", "manager": { "_id": "ObjectId_for_Manager1", "name": "Karthik", "type": "Manager" } }
Controller
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');
Where controller is referenced:
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 });
}
});
NOTE : Cannot able to access property of an object using mongoose. I was able get response with http:localhost:3000/api/site but not with http:localhost:3000/main.Instead I get this error :
{"error":"Cannot read properties of undefined (reading ‘status’)"}
2
Answers
I’m not sure of my answer because I can’t run the code.
but as I can see, you’ve already responded to the coming request inside
getAllSites
controller.once you send a
response
the request-response cycle gets closed, therefore this line of code :doesn’t get the
sites
value that it expected and waited for becausegetAllSites
does close the request-response cycle, it doesn’t return any value.I think you should reorganise your code.
I can’t see any point in creating a whole controller just to do this line:
const sites = await Site.find();
you may consider doing it like this: (in my opinion it’s more cleaner)
then move all the code to be inside
getAllSites
and at the end, send the response from there just like you did.or modify your controller to be like this :
I hope my answer can be some kind of help to you and others
You’re sending a response from the
getAllSites
controller, once you send a response the request-response cycle gets closed that’s why theresponse.render()
that is inside the router can’t be processedI’ve reorganised your code a little, please try out it and inform me if it worked out or not :