我只是無法弄清楚這有什麼問題。有誰知道我爲什麼會遇到這個錯誤?我正在使用Node,Express,MongoDB和Mongoose。問題迭代MongoDB對象數組
下面是代碼,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 protected]",
"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: '[email protected]',
__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)
我無法找到一個答案,我可以不會發現錯誤,所以如果這是一個重複的問題,我很抱歉。並感謝您的幫助。
典型的原因是您定義的模式與文檔結構不匹配。你應該真的修復模式(這是從問題中缺少的),但在一個捏,添加'.lean()'即。 'User.findById(req.user._id).lean()。exec(function(err,foundUser){..' should you give you a immediate workaround。Show the schema if you need the correction corrected。 –
你似乎有是正確的Neil,我重寫了模式的這一部分,現在它正在工作,非常感謝,並且感謝'.lean()'上的這個技巧。 – Inertia
這真的是關於你的模式的問題。在您的模式中與您存儲的數據的形狀不匹配,您可以交替使用像'founduser.get('purchases')'這樣的方法來處理未正確定義的事物,並且沒有默認分配的訪問器,因爲「形狀」不匹配,但對「模板」沒有任何幫助,因此您可以使用'.lean()'或其他方法將存儲的數據轉換爲「原始」JavaScript對象,或者簡單地修復架構 –