I'm working on a simple node.js app that's storing data with mongodb. I'm not having any trouble adding new records to the database, or with displaying database records using ejs. However, I'd like to use data from my database (a list of words, incidentally) on the front end. Specifically, I'd like to push the results of a query into an array, which I can use in a front-end js file. Is this possible?
Here's the GET route:
app.get("/wordlist", function (req, res) {
Word.find({}, function(err, allWords){
if(err){
console.log(err);
} else {
res.render("index", {words: allWords});
}
});
});
And here's the simple loop I'm using to display the data in an ejs file:
<% words.forEach(function(foo){ %>
<p><%= foo.word + " " + foo.category + " " + foo._id %></p>
<% }); %>
Thank you so much!
allWordsis an array that you stored inwordsthat will be passed to your view, sowordsis an array. I don't follow.allWordsinwords, but I can only use that in my ejs markup. What I want is to be able to use thewordsvariable in my plain old javascript file. In other words, if I typewordsinto the browser console, I want to see the contents of the variable instead of getting a "not defined" error. Does that make sense? Or should I try again?