【问题标题】:NodeJs - how to populate the model view with data from another modelNodeJs - 如何使用来自另一个模型的数据填充模型视图
【发布时间】:2021-06-09 06:55:14
【问题描述】:

我正在通过制作一个简单的库存应用程序来练习 Node,其中我有 3 个模型:Item、Category 和 Manufacturer。我想要做的是,在显示项目详细信息时,包括与该特定项目关联的类别和制造商,但似乎我无法使其工作。任何帮助将不胜感激。

这是项目控制器

const Item = require("../models/item");
const Category = require("../models/category");
const Manufacturer = require("../models/manufacturer");

const async = require("async");

exports.index = function (req, res) {
  res.render("index", { title: "StrinGuist" });
};

//display list of all items
exports.item_list = function (req, res, next) {
  Item.find({}, "name description category in_stock price manufacturer")
    .populate("item")
    .exec(function (err, list_items) {
      if (err) {
        return next(err);
      }
      res.render("item_list", { title: "All items", item_list: list_items });
    });
};

//display detail page for a specific item
exports.item_detail = function (req, res, next) {
  async.parallel(
    {
      item: function (callback) {
        Item.findById(req.params.id)
          .populate("category")
          .populate("manufacturer")
          .exec(callback);
      },
    },
    function (err, results) {
      if (err) {
        return next(err);
      }
      if (results.item == null) {
        // No results.
        const err = new Error("Item not found");
        err.status = 404;
        return next(err);
      }
      // Successful, so render.
      res.render("item_detail", {
        title: results.item.name,
        item: results.item,
      });
    }
  );
};

这是视图(哈巴狗)

extends layout 

block content 
  h1 #{item.name}

  div(class='item-detail-content')
    p #[strong Price: $] #{item.price}
    p #[strong Description: ] #{item.description}
    p #[strong In stock: ] #{item.in_stock}
    p #[strong Manufacturer: ] #{item.manufacturer.name}
    p #[strong Category: ] #{item.category.name}

这会引发错误“无法读取 null 的属性 'name'”,但我不太确定出了什么问题。我还尝试将类别和制造商名称声明为“虚拟”,但这也不起作用。

【问题讨论】:

    标签: javascript node.js express model controller


    【解决方案1】:

    对于像 mongoose 这样的 ORM,在使用 mongodb 时,您可以使用 populate 方法允许您这样做。

    https://mongoosejs.com/docs/populate.html

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2021-11-19
      相关资源
      最近更新 更多