【发布时间】:2021-03-19 05:11:55
【问题描述】:
我试图在聚合和计数后填充。
这些是我的模型:
用户日志
const UserLog = new Schema(
{
title: {
type: String,
required: true,
trim: true,
},
article: {
type: mongoose.Schema.ObjectId,
ref: 'Article',
required: true,
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
},
{ timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
文章
const Article = new Schema(
{
title: {
type: String,
required: true,
trim: true,
},
content: {
type: String,
required: true,
},
},
{ timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
我正在运行这样的查询:
export const getCountByArticle = async () => {
const articles = await UserLog.aggregate([
{
$group: { _id: '$article', count: { $sum: 1 } },
},
]);
return articles;
};
查询返回:
[
{
"_id": "5fcbc12dd895b528289723e6",
"count": 1
},
{
"_id": "5fccefc375c47a3fd49c083d",
"count": 2
}
],
问题是我想用实际文章“填充”_id 字段。我试过 $lookup,但它返回一个包含所有文章的数组,我不想要那个。放松对我也不起作用。下面是我真正想要的结果。
[
{
"_id": "5fcbc12dd895b528289723e6",
"title": "Title",
"content": "contentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontent",
"count": 1
},
{
"_id": "5fccefc375c47a3fd49c083d",
"title": "Title",
"content": "contentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontent",
"count": 2
}
],
我真的希望有人可以帮助我。提前致谢。
【问题讨论】:
标签: javascript node.js mongodb mongoose aggregation-framework