I just can't figure out what's wrong with this. Does anyone know why I get this error? I'm using Node, Express, MongoDB with Mongoose.
Here's the code, the console.log()
lines are just to debug and they are what throw the error.
// report view
app.get("/report", isLoggedIn, function(req, res){
User.findById(req.user._id, function(err, foundUser){
if(err){
console.log(err);
console.log(foundUser);
} else {
console.log(foundUser);
console.log();
console.log(foundUser.purchases[0].phrase);
res.render("report.ejs", {user:foundUser});
}
});
});
Here's the user
document in MongoDB:
{
"_id" : ObjectId("59d4dc48fba3ef12437bf4b1"),
"salt" : "30dd9c9942...",
"hash" : "8c8c96d88a708...",
"username" : "Christian Lewis",
"email" : "email@email.com",
"signupDate" : ISODate("2017-10-04T13:04:08.167Z"),
"__v" : 6,
"purchases" : [
{
"phrase" : "Porche 918 Spyder",
"location" : "South Yarra"
},
{
"phrase" : "Blinds",
"location" : "United Kingdom"
}
]
}
And here's everything that comes out of the console:
{ _id: 59d4dc48fba3ef12437bf4b1,
username: 'Christian Lewis',
email: 'christianllewis@gmail.com',
__v: 6,
signupDate: 2017-10-04T13:04:08.167Z,
purchases:
[ { location: 'South Yarra', phrase: 'Porche 918 Spyder' },
{ location: 'United Kingdom', phrase: 'Blinds' } ] }
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'phrase' of undefined
at /Volumes/Store/Lickety-Split/website/app.js:58:47
at Query.<anonymous> (/Volumes/Store/Lickety-Split/website/node_modules/mongoose/lib/model.js:3841:16)
at /Volumes/Store/Lickety-Split/website/node_modules/kareem/index.js:273:21
at /Volumes/Store/Lickety-Split/website/node_modules/kareem/index.js:131:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
I can't find an answer to this, I can't spot the error, so I apologise if this is a duplicate question. And thank you for any help.
The error is happening on this line
console.log(foundUser.purchases[0].phrase);
This would suggest foundUser.purchases
array is empty, however based on your data logged, it is not.
Can you confirm that that the data posted is in fact the correct log information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.