我正在与Mongoose合作开发一个MongoDB数据库. 我有一个Category模型,其中嵌套子类别(SubDocuments)

    const schema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    children: [
      {
        title: {
          type: String,
          required: true,
        },
      },
    ],
  },
  {
    timestamps: true,
  }
)

以及具有引用Category模型的Category字段的产品模型

const schema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
   
    categories: [{ type: mongoose.Schema.Types.ObjectId, ref: "Category" }],
   
  },
  {
    timestamps: true,
  }
);

类别数组包含同时属于顶级类别和类别的多个_id字段->子类别

但是当我try 填充产品时.类别:

 Product.find()
      .populate('categories')

我只获得顶级类别,而不是嵌套子类别.

我如何也填充嵌套级别?

我试过:

Product.find()
      .populate({
        path: "categories",
        model: "Category",
        populate: {
          path: "children",
          model: "Category",
        },
      })

但它并没有奏效.结果都是一样的

推荐答案

您的Category.children是具有一个title属性的对象array.这些不是referenced documents个.在内部,您正在请求Mongoose在categories集合上执行查找.它希望在Category.children数组中找到ObjectId,以与categories集合中的_id字段进行匹配.

如果您希望保持populate()查询的原样,并且编写正确,那么您需要修改您的模式以将ObjectId存储在children数组中.就像这样:

    children: [{ 
      type: mongoose.Schema.Types.ObjectId, 
      ref: "Category" 
   }],

目前,您的模式设置为将Category.children存储为subdocuments的数组,而不是引用的文档.

Mongodb相关问答推荐

MongoDB Aggregate-如何在条件中替换字符串中的变量

Mongodb Timeseries / Golang - ['timestamp' 必须存在并包含有效的 BSON UTC 日期时间值]

如何 db.getUser() 使用 go mongo-driver

Mongodb,在一个查询中用正则表达式更新部分字符串

如何在 mongodb golang 的单个更新调用中使用 $set 和 $inc?

MongoDB 存储大量指标/分析数据的方法

Mongo C#忽略属性

我怎样才能排序空值在 mongodb 中是最后排序的?

mongodb 中的 --bindip 配置选项有什么作用?

Mongodb:查询嵌套在数组中的json对象

使用 ObjectId.GenerateNewId() 还是离开 MongoDB 创建一个?

在 Mongoose 中填写所有必填字段

如何在 Mongoose 中更新数组值

NumberLong和简单整数之间的MongoDB区别?

在 MongoDB 中快速搜索数十亿个小文档的策略

spring 数据MongoDB.生成id的错误

如何在 Ubuntu 10.04 中使用 --auth 选项重新启动 mongodb?

MongoDB打印两点之间的距离

查找聚合性能差

MongoDB Compass:select distinct field values