在猫鼬查询中填充不同的字段

问题描述 投票:0回答:1

我有以下型号:

用户:

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

我想查询所有博客并填充其作者字段、评论字段以及评论中的作者字段。我尝试这样做:

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

但它不起作用,我做错了什么?如果您有任何建议请告诉我。

javascript mongodb mongoose mongodb-query mongoose-populate
1个回答
0
投票

你必须像这样嵌套填充:

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 
      }
   });
© www.soinside.com 2019 - 2024. All rights reserved.