2014-04-19 46 views
0

我想在foreach在頁面上展示我收藏的內容,但我有一個錯誤:的NodeJS +蒙戈 - 得到收集/沒有方法的foreach

TypeError: Object # has no method 'forEach'

my_express.get('/Profil', isLoggedIn, function(req, res) { 

_articles.findOne({ email : req.user.email }, function(error, articles) { 

if (error || !articles) { 
    res.render('Profil', {user : req.user, articles : articles}); 
} 

else { 
    res.render('Profil', { user: req.user, articles : articles}); 
} 

而我的觀點是:

<% articles.forEach(function(content){ %> 
<p><%= content.Titre %></p> 
<p><%= content.Description %></p><% }); %> 
+0

嘗試使用'find'而不是'findOne'。 – JohnnyHK

+0

我嘗試使用查找,它不起作用。我在查看頁面上收到,未定義的值 – solidsnake

回答

0

當使用findOne,其結果將是一個對象,而不是一個陣列,而「的forEach」是數組原型的方法。而當你使用發現,沒有直接的回調,你會喜歡的東西:

_articles.find({ email : req.user.email }).toArray(function(error, articles) { 
    if (error || !articles) { 
     res.render('Profil', {user : req.user, articles : articles}); 
    } else { 
     res.render('Profil', { user: req.user, articles : articles}); 
    } 
}); 

,而不是「指定者」你可以使用「每個」在這種情況下,回調將每個項目調用一次,該項目將成爲一個對象,就像findOne案例一樣。

希望有所幫助。

+0

非常感謝。 – solidsnake

+0

太棒了!歡迎您:D – jmdiego