首页 > 解决方案 > 集合之间的 .populate() 连接没有出现

问题描述

有点挣扎从猫鼬填充。一直在查看各种教程和文档,但仍然不明白问题所在。我有 2 个模型:项目和类别。

Item.js 模型

const mongoose = require("mongoose");

const ItemSchema = new mongoose.Schema({
  child: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "category",
  },
  name: {
    type: "String",
    unique: true,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = Item = mongoose.model("item", ItemSchema);

Category.js 模型

const mongoose = require("mongoose");

const CategorySchema = new mongoose.Schema({
  name: {
    type: "String",
    required: true,
    unique: true,
  },
  price: {
    type: "String",
  },
});

module.exports = Category = mongoose.model("category", CategorySchema);

所以据我所知,如果我创建一个项目,然后如果我创建这样的类别:

router.post("/:name", async (req, res) => {
  let category = new Category({
    name: req.params.name,
  });
  await category.populate("category").save();
  res.send(category);
});

我应该能够对项目提出请求,并且我也应该能够看到类别?因为现在如果我向项目发出获取请求,我只能看到项目属性。

标签: node.jsmongodbmongoose

解决方案


推荐阅读