简体   繁体   English

如何填充数组内部的 object 和 mongoose 中的另一个数组中的所有用户字段

[英]How to populate all the user fields which is inside an object inside of an array and another array in mongoose

here is my course schema这是我的课程架构

const CourseSchema = new Schema(
  {
    courseName: {
      type: String,
      required: true,
      lowercase: true,
    },
    comments: [
      [
        {
          user: {
            type: Schema.Types.ObjectId,
            ref: "Users",
            required: true,
          },
          comment: {
            type: String,
            required: true,
          },
          createdAt: {
            type: Date,
            required: true,
          },
        },
      ],
    ],
  },
  {
    timestamps: true,
  }
);
const Course = mongoose.model("Course", CourseSchema);

I want to populate the user field.我想填充用户字段。 I've tried many stack overflow solutions but none of them works for me.我尝试了许多堆栈溢出解决方案,但没有一个对我有用。

I populated the model like this but, doing so it only populates the first index the of every model.我像这样填充了 model,但是这样做只会填充每个 model 的第一个索引。 courses = await Course.findOne({}).populate({ path: "comments.0.0.user", });课程 = 等待 Course.findOne({}).populate({ path: "comments.0.0.user", });

You can populate another level deeper, here's what you need to do:您可以更深入地填充另一个级别,这是您需要做的:

 db.Course.findOne({}).populate({"path":"comments",populate:[{
    path:"user",
     model:"Users"
    }]})

Another way of nested populating data:另一种嵌套填充数据的方式:

db.Course.findOne({}).populate("comments.user")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将元素推入 Mongoose 中另一个数组中的 object 中的数组? - How to push an element into an array inside an object inside another array in Mongoose? 更改 mongoose 中数组内部 object 的字段 - change fields of object inside array in mongoose 如何将一个数组推入另一个数组内部的对象中? - How to push an array into an Object which is inside of another array? 我如何将 object 推入 object 内的数组,该数组也在另一个数组内 - How do i push an object into an array which is inside an object which is also inside an another array 如何在猫鼬中查询对象数组内的值 - how to query value inside of object array in mongoose 如何在 mongoose 的数组中返回匹配的 object - How to return a matched object inside an array in mongoose 如何在猫鼬的对象数组中搜索对象? - how to search an object inside an array of objects in mongoose? 如何在子文档中填充模型实例数组? MongoDB 猫鼬 - How to populate an array of model instances inside a subdocument? MongoDB Mongoose 如何访问对象数组内的对象,该对象数组在JavaScript中的另一个数组内? - how to access object inside an object Array which is inside another array in javascript? 在Mongoose模式中的另一个数组内写入一个数组 - Write an array inside another array in a Mongoose Schema
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM