如何在$ Mongoose中$查找后过滤对象字段上的查询基础
我想获得一个以顶级(速率)排序的博客的评论 评论模型:
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,
}
},
])
但是$ tookup后不接受$匹配!我也尝试使用“ $ filter”,但是它会得到一个“数组”,并且有一个对象! 我的查询工作没有$匹配。但是需要过滤基于博客ID的评论
I want to get comments of a post-blog sorted by top-like(rate)
Comment Model:
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}
})
my query:
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,
}
},
])
but $match after $lookup isn't accept! I try to use "$filter" also, but it get a "array " and a have a Object!
my query work without $match. but a need to filter comments base on blog-id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你能尝试一下吗?
Can you try this,