繁体   English   中英

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

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

这是我的课程架构

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);

我想填充用户字段。 我尝试了许多堆栈溢出解决方案,但没有一个对我有用。

我像这样填充了 model,但是这样做只会填充每个 model 的第一个索引。 课程 = 等待 Course.findOne({}).populate({ path: "comments.0.0.user", });

您可以更深入地填充另一个级别,这是您需要做的:

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

另一种嵌套填充数据的方式:

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM