朋友们,下午好!
我正在学习 MongoDB,现在我面临以下问题:
有一个数据库,其中帖子和单独的评论分别存储。
岗位方案:
const PostSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
text: {
type: String,
required: true,
},
tags: {
type: Array,
default: [],
},
viewsCount: {
type: Number,
default: 0,
},
commentsCount: {
// Счетчик совпадений по _id поста.
},
imageUrl: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
},
{
timestamps: true,
}
);
export default mongoose.model("Post", PostSchema);
评论方案:
const CommentSchema = new mongoose.Schema(
{
text: {
type: String,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true,
},
},
{
timestamps: true,
}
);
我需要在帖子模型的字段中commentsCount
显示来自它的评论数_id
。