我无法弄清楚这有什么问题。有谁知道我为什么会收到这个错误?我使用Node,Express,MongoDB和Mongoose。
这里是代码,console.log()
行只是为了调试,它们是抛出错误的原因。
// 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});
}
});
});
这是MongoDB中的user
文档:
{
"_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"
}
]
}
以下是控制台发出的所有内容:
{ _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)
我无法找到答案,我无法发现错误,所以如果这是一个重复的问题我会道歉。谢谢你的帮助。
答案 0 :(得分:0)
错误发生在这一行
console.log(foundUser.purchases[0].phrase);
这表明foundUser.purchases
数组为空,但是根据您记录的数据,它不是。
您能否确认发布的数据实际上是正确的日志信息。