我想得到一个博客的评论按顶部(率)的评论模式排序:
const CommentSchema = new Schema({
content: {type: String, maxLength: 100, required: true},
user: {type: Schema.Types.ObjectId, ref: 'User', required: true },
blog: {type: Schema.Types.ObjectId, ref: 'Blog', required: true},
reactions: [{type: Schema.Types.ObjectId, ref: 'Reaction'}],
},{ timestamps: true})
const ReactionSchema = new Schema({
user: {type: Schema.Types.ObjectId, ref: 'User', required: true},
comment: {type: Schema.Types.ObjectId, ref: 'Comment', required: true},
date: {type: Schema.Types.Date, default: Date.now, required: true}
})我的问题是:
this.model.Reaction.aggregate([
{
$group: {
_id: "$comment",
num: { $sum: 1 }
}
},
{ $sort: { num: -1 } },
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "_id",
as: "Com",
}
},
{ $unwind: "$Com" },
{
$match: {"Com.blog": '629af177e03ab4cfe845a9a4'}
},
{
$project: {
content: "$Com.content",
num: 1,
}
},
])但是$match在$lookup之后是不接受的!我也尝试使用"$filter“,但是它得到了一个”数组“和一个有一个对象!我的查询不需要$match。但是需要基于blog-id对评论进行过滤。
发布于 2022-06-05 15:51:32
你能试试这个吗
this.model.Reaction.aggregate([
{
$group: {
_id: "$comment",
num: { $sum: 1 }
}
},
{ $sort: { num: -1 } },
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "_id",
as: "Com",
}
},
{ $unwind: "$Com" },
{
$match: {"Com.blog": mongoose.Types.ObjectId('629af177e03ab4cfe845a9a4')}
},
{
$project: {
content: "$Com.content",
num: 1,
}
},
])https://stackoverflow.com/questions/72504771
复制相似问题