I'm building something where I need to query stuff from MongoDB and display the results in the Frontend using EJS template in node.js.
Everything goes well when querying the results. All the array values are returned when I console.log()
them but on the frontend using EJS template, just one value is returned.
Here is my code for Querying the result:
app.get('/', function (req, res) {
user.find({}, { __v: 0, _id: 0}, function (err, result) {
if (err) throw err;
result.forEach(function(u) {
console.log(u.imgs);
res.render('pages/index',{
path: u.imgs,
state: req.session.state
});
});
});
My code in EJS:
<% for(var i=0; i<path.length; i++) { %>
<%= path[i] %>
<% } %>
This is the code in the user
var userSchema = mongoose.Schema ({
imgs: String
})
What do you think is wrong with my code?
Remove the forEach loop in your query and map the results array on the path attribute ie
app.get('/', function (req, res) {
user.find({}, { __v: 0, _id: 0}, function (err, result) {
if (err) throw err;
res.render('pages/index',{
path: result.map(u => u.imgs),
state: req.session.state
});
});
});
You need HTML tags like
<ul>
<% for(var i=0; i<path.length; i++) {%>
<li><%= path[i] %></li>
<% } %>
</ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.