Passing Mongodb Data Into .ejs With Node.js
Route: app.get('/admin/cardapio', function(req, res) { Produtos.find({}).exec(function(err, produtos) { if (err) throw err; res.
Solution 1:
Route .js
app.get('/admin/cardapio', function(req, res) {
Produtos.find({}, function(err, produtos) {
if (err){
console.log(err);
}else{
res.render('admin/cardapio.ejs', { data: produtos});
}
});
});
EJS file
<% data.forEach(function(foundData, i){%>
<tr><td><%= foundData.title %></td></tr>
<%}%>
Can you test?
Solution 2:
use forEach loop as below :
<% data.forEach(function(product){ %>
<tr><td><%= product.title %></td><td><%= product._id %></td><td><%= product.description %></td><td><%= product.type %></td><td><%= product.price %></td><td>EDITAR / REMOVER</td></tr>
<%})%>
or if you want to use for loop :
<% for (var i = 0; i < data.length; i++) {%>
<tr><td><%= data[i]["title"] %></td><td><%= data[i]["_id"] %></td><td><%= data[i]["description"] %></td><td><%= data[i]["type"] %></td><td><%= data[i]["price"] %></td><td>EDITAR / REMOVER</td></tr>
<%}%>
Solution 3:
The presence of "__v" : 0
in your MongoDB and the .exec()
methods that you're using implies that you're using Mongoose as an ODM (can you confirm this to me ?).
The result that your query returns is not a JSON Object but a Mongoose model instance. That's why you need to call .toJSON()
on your result :
res.render('admin/cardapio.ejs', { data: produtos.map(p => p.toJSON()) });
Solution 4:
Try to lean Your result, it converts mongoose objects to generic json objects
app.get('/admin/cardapio', async (req, res) => {
try {
const products = await Produtos.find({}).lean();
res.render('admin/cardapio', {products});
}
catch (error) {
console.error(error);
res.status(500).send('Oops..');
}
});
EJS file
<% products.forEach(function(product, index) { %>
<tr><td><%= product.title %></td><td><%= product.description %></td><td><%= product.type %></td><td><%= product.price %></td><td><ahref="/path/to/edit/<%= product._id %>">EDITAR</a>
/
<ahref="/path/to/delete/<%= product._id %>">REMOVER</a></td></tr>
<% }) %>
Post a Comment for "Passing Mongodb Data Into .ejs With Node.js"