Question

I have this code on app.js that's a callback where all the content of the "locale" collection is found:

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

This sets the "title" variable when "index" (the homepage) is accessed and pass the "locale" collection content to the variable "content" "stringifying" it beforehand (if I don't, I get [object],[Object]):

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

And this forEach in the view "index.ejs" which should only return the "title" collections field as a result:

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

Anyway the problem is that I get a "'TypeError' has no method 'forEach'" when I browse the page.. What could cause this behavior? Thank you!

Was it helpful?

Solution

You're stringifying the locale object before rendering it. Strings have no forEach method, only arrays! So long as you don't actually plan on printing the whole content object to the page, and assuming that locale is a Javascript object, you can skip the stringify part entirely, and just do:

res.render('index', {title: "This is a test server", content: locale});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top