Node.js-Ejs-Mongojs堆栈上的“没有方法”forEach“TypeError”

我在app.js上有这个代码,这是一个callback“locale”集合中的所有内容:

tester = function(callback) { db.locale.find({}, function(err, locale) { callback( null, locale ) }); }; 

当“index”(主页)被访问时,这将设置“标题”variables,并将“locale”集合内容事先传递给“内容”variables“string化”的variables(如果我不知道,我得到[object],[目的]):

 app.get('/', function(req, res) { tester(function(err, locale) { res.render('index', {title: "This is a test server", content: JSON.stringify(locale)}); }); }); 

而这个forEach在“index.ejs”视图中应该只返回“title”集合字段,结果是:

 <ul> <% content.forEach( function( item ){ %> <li><%= item.title %></li> <% }); %> </ul> 

无论如何,问题是我得到一个“'TypeError'没有方法'forEach'”当我浏览页面..什么可能导致这种行为? 谢谢!

您在呈现之前将locale对象string化。 string没有forEach方法,只有数组! 只要你不打算把整个content对象打印到页面上,并且假设locale是一个Javascript对象,那么你可以完全忽略stringify部分,只需要:

 res.render('index', {title: "This is a test server", content: locale});