【问题标题】:Why is my ejs template not showing the associated data?为什么我的 ejs 模板没有显示相关数据?
【发布时间】:2020-11-08 03:52:07
【问题描述】:

我为库存制作了一个展示页面

<% inventory.products.forEach(function(product) { %>
        <div class="card">
            <img src="<%= product.image %>" alt="" class="card-img-top" />
            <div class="card-body">
                <h5 class="card-title">
                    <%= product.name %>
                </h5>
            </div>
        </div>

        <% }) %>

但页面没有显示任何产品图片和名称 (我的pagedb的截图)

我的库存数据库的代码是:

let mongoose = require("mongoose");

let inventorySchema = new mongoose.Schema({
  id: {
    type: mongoose.Schema.Types.ObjectId,
  },
  author: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    username: String,
  },
  products: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Product",
    },
  ],
});
module.exports = mongoose.model("Inventory", inventorySchema);

【问题讨论】:

  • 您可以在获得库存的地方添加代码吗? Inventories.find ...
  • 感谢我发现我没有正确传递产品数组

标签: node.js mongodb express ejs web-development-server


【解决方案1】:

稍微澄清一下,您是否需要在您的页面路由上导出 db 的模块,并且您是否创建了文档?据我所知,您导出了一个 mongoose 模型,我想知道是否创建了由您刚刚导出的 db 模型创建的文档。

如果您没有创建文档,那么您尝试执行的操作将不起作用。

您需要从数据库中检索根据架构创建的产品数组,并将产品分配为键。完成后,使用您共享的 ejs 文件循环浏览应从数据库中获取的产品。

我希望这很清楚并且有帮助。

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多