问题描述
有谁知道为什么这种聚合仅匹配帖子,却不填充评论?
我需要评论集合中的用户评论,但只有空管道返回评论
Post.aggregate(...)
[
{
"$match": {
"author": ObjectId(...)
}
},{
"$lookup": {
"from": "comments","let": {
"postID": "$post","isHiden": "$isHiden"
},"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$_id","$$postID"
]
},{
"$eq": [
"$$isHiden",0
]
}
]
}
}
}
],"as": "comments"
}
}
]
评论对象包含
{
"_id": "5f7de8491af5c0e246d42609","isHiden": false,"text": "...","post": "5f7de8491af5c0e246d42605"
}
帖子模型是
{
"_id": "5f7de8491af5c0e246d42605","title": "Corporate Web Coordinator","body": "...","author": "5f7de8491af5c0e246d42602"
}
}
我想得到像这样的结果
{
"_id": "5f7de8491af5c0e246d42605","confirm_status": "pending","title": "Dynamic Marketing Supervisor","author": "5f7de8491af5c0e246d42604","comments": [
{ "_id": "5f7de8491af5c0e246d42609","post": "5f7de8491af5c0e246d42605" }
]
}
我尝试了一切,但无济于事...
我将不胜感激
解决方法
问题出在您的查询中,
- post字段出现在注释表中,并且您使用了_id,因此应为
$post
, - 内部管道字段
isHiden
在发布表中不存在,您正在let
中定义该字段,
$lookup: {
from: "comments",let: { postID: "$_id" },pipeline: [
{
$match: {
$expr: [
{
$eq: [
"$$postID","$post"
]
}
],isHiden: false
}
}
],as: "comments"
}