我有以下型号:

用户:

const userSchema = new mongoose.Schema(
  {
    name: { type: String, min: 3, max: 20, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, min: 3, max: 50, required: true },
    blogs: [
      {
        type: mongoose.SchemaTypes.ObjectId,
        type: String,
        ref: "Blog",
        required: false,
        default: [],
      },
    ],
    comments: [
      {
        type: mongoose.SchemaTypes.ObjectId,
        type: String,
        ref: "Comment",
        required: false,
        default: [],
      },
    ],
  },
  { timestamps: true, collection: "users" }
);

方法:

const commentSchema = new mongoose.Schema(
  {
    title: { type: String, min: 1, max: 25, required: true },
    content: { type: String, min: 1, max: 250, required: true },
    author: {
      type: mongoose.SchemaTypes.ObjectId,
      ref: "User",
      required: true,
    },
    blogRef: { type: mongoose.SchemaTypes.ObjectId, ref: "Blog" },
  },
  { timestamps: true, collection: "comments" }
);

博客:

const blogSchema = new mongoose.Schema(
  {
    title: { type: String, min: 3, max: 20, required: true },
    content: { type: String, required: true },
    likes: { type: Number, required: true, default: 0 },
    author: { type: mongoose.SchemaTypes.ObjectId, ref: "User" },
    comments: [
      { type: mongoose.SchemaTypes.ObjectId, ref: "Comment", default: [] },
    ],
  },
  { timestamps: true, collection: "blogs" }
);

我想查询所有的博客,并在 comments 中填充它们的作者字段、 comments 字段和作者字段.我试着这样做:

const blogs = await Blog.find()
  .populate("author")
  .populate("comments")
  .populate("author");

但它没有起作用,我做错了什么?如果你有什么建议,请让我知道.

推荐答案

你必须像这样嵌套种群:

const blogs = await Blog.find()
  .populate('author')
  .populate({
      path: 'comments',
      populate: { 
         path: 'author' 
      }
   });

如果模型尚未注册,则可以按如下方式显式传递它们:

const blogs = await Blog.find()
  .populate({path: 'author', model: User})
  .populate({
      path: 'comments', model: Comment,
      populate: { 
         path: 'author', model: User 
      }
   });

Javascript相关问答推荐

详细更改参考价值:"

想要检测字符串中的所有单词

如何在非独立组件中使用独立组件?

用户单击仅在JavaScript中传递一次以及其他行为

为什么使用MAX_SAFE_INTEGER生成随机整数时数字分布不准确?

容器如何更改默认插槽中子项的显示?

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

yarn安装一个本地npm包,以便本地包使用main项目的node_modules(ckeditor-duplicated-modules错误)

为什么ngModel不能在最后一个版本的Angular 17上工作?'

嵌套异步JavaScript(微任务和macrotask队列)

如何在不创建新键的情况下动态更改 map 中的项目?

当试图显示小部件时,使用者会出现JavaScript错误.

Javascript json定制

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

如何限制显示在分页中的可见页面的数量

如何使用基于promise (非事件emits 器)的方法来传输数据?

第一项杀死下一项,直到数组长度在javascript中等于1

如何访问此数组中的值?

是否可以将Select()和Sample()与Mongoose结合使用?

更改agGRID/Reaction中的单元格格式