使用node.js将MongoDB数据传递到.ejs [英] Passing MongoDB data into .ejs with node.js

查看:61
本文介绍了使用node.js将MongoDB数据传递到.ejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

路线:

        app.get('/admin/cardapio', function(req, res) {
            Produtos.find({}).exec(function(err, produtos) {
                if (err) throw err;
                res.render('admin/cardapio.ejs', { data: produtos});
            });
        });

表格:

                <% for (var i = 0; i < data.length; i++) {%>
                  <tr>
                    <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>
                  <%}%>

Mongo DB结果:

Mongo DB result:

{
    "title" : "teste",
    "description" : "teste",
    "price" : "20",
    "type" : "teste",
    "_id" : ObjectId("5b2790f7f9f2ab37e813504d"),
    "__v" : 0
}

当我在每行上仅使用 data [i] 时,它会显示整个结果,但是如果我输入 .title ,它不会显示任何内容,并且当我从mongodb中放入 _id 时,它会正常显示

When I use only data[i] on each row, it shows the whole result, but If I put the .title it doesn't show anything, and when I put _id from mongodb it shows normally

在第一列中带有 data [i] ._ id

推荐答案

尝试倾斜您的结果,它将猫鼬对象转换为通用json对象

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文件

<% products.forEach(function(product, index) { %>
  <tr>
    <td><%= product.title %></td>
    <td><%= product.description %></td>
    <td><%= product.type %></td>
    <td><%= product.price %></td>
    <td>
      <a href="/path/to/edit/<%= product._id %>">EDITAR</a>
      / 
      <a href="/path/to/delete/<%= product._id %>">REMOVER</a>
    </td>
  </tr>
<% }) %>

这篇关于使用node.js将MongoDB数据传递到.ejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆