我有以下型号:
用户:
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");
但它没有起作用,我做错了什么?如果你有什么建议,请让我知道.