我有一个 mongodb 数据库,其中包含一个“posts”集合和一个“comments”集合。每条评论都属于一个基于评论集合中的“postID”字段的帖子。以下是每个模型的外观:
发布:
{
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
body: { type: String, required: true, trim: true },
image: { type: String },
likes: { type: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }] },
},
评论:
{
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true,
},
body: { type: String, trim: true, required: true },
},
当我查询帖子时,我还想返回该帖子的评论数量(不是实际评论本身,只是数量)。目前我有一个看起来像这样的聚合:
{ $skip: (parseInt(page) - 1) * parseInt(pageSize) },
{ $limit: parseInt(pageSize) },
{
$lookup: {
from: "users",
localField: "author",
foreignField: "_id",
as: "author",
},
},
{ $unwind: "$author" },
{
$project: {
author: {
_id: true,
username: true,
profileImage: true,
},
body: true,
createdAt: true,
location: true,
image: true,
numOfLikes: {
$size: "$likes",
},
isLiked: {
$in: [mongoose.Types.ObjectId(userID), "$likes"],
},
},
},
有没有一种方法可以查询同一聚合中每个帖子的评论数量?我尝试在帖子集合中有一个“评论”数组,它只包含评论 ID,然后只使用 $size 运算符来获取每个帖子的评论数量。但是,由于我将相似的数据保存在两个单独的集合中,因此在执行其他操作(例如删除)时会导致一些问题,这并不是最干净的解决方案。
感谢任何可以提供帮助的人!