Here is my GET request handler, to render a page:
app.get("/:band", async (req, res) => {
const page = req.params.band;
try {
const result = await db.query("SELECT * FROM artists");
const artistData = result.rows;
const band = artistData.findIndex((info) => info.onewordid === page);
const bandInfo = artistData[band];
console.log(bandInfo);
const articlesresult = await db.query("SELECT * FROM articles WHERE artist_id = $1",
[bandInfo.id]);
res.render("artistpage.ejs", {
artistinfo: bandInfo,
data: artistData,
articles: articlesresult.rows,
});
} catch(err){
console.log(err)
}
});
An example band object:
{
id: 1,
name: 'The Rolling Stones',
picadress: 'backgroundpic2.jpeg',
onewordid: 'stones'
}
The error/output:
undefined
TypeError: Cannot read properties of undefined (reading 'id')
at file:///Users/admin/Downloads/Web%20development%20Project/Backend/Blog%20Project%20Styling/index.js:83:15
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Why can I console log this, but I get bandInfo.id as "undefined"?
2
Answers
Try
bandInfo[0].id
instead ofbandInfo.id
in the second query.Consider these four lines of code.
I believe the
console.log(...)
statement is printingundefined
into your output, just before the error information is printed into your output.I also believe the third line assigning to
bandInfo
is actually incorrectly indexing intoartistData
, becauseartistData
is a reference toresult.rows
.Line 3 which assigns to
band
is already looking up the target object/row from the results, so you shouldn’t need to re-index the rows a second time.Consider simplifying your code as follows:
In this version of the code you do not need
page
norartistData
, these temporary assignments meant to simplify the code actually increase complexity. That’s not a solution to your problem, however. The solution here is to perform the lookup (usingfindIndex(...)
) and assign it directly tobandInfo
.As a debugging aid, before making any other changes, you could change the
console.log(...)
to give yourself better information:Lastly, how to interpret this error:
TypeError: Cannot read properties of undefined (reading 'id')
This means that while trying to read the property
id
the parent reference was undefined. Given your code, this expression would be the only which could be the problem:bandInfo.id
, and again, the sample logging you provided forconsole.log(bandInfo)
is printingundefined
beforeconsole.log(err)
prints the error information.Good luck!