在MongoDB中,我有如下文档(注释):
{
"_id": { "$oid": "61acd4474bbaa88d12c38199" },
"textContent": "This comment has 2 replies",
"replies": [
{ "$oid": "61acd57fe06fed9e70462139" },
{ "$oid": "61acd57fe06fed9e7046213a" },
"__v": 0
}
所有注释都存储在同一类型的对象中,具有一个数组“replies”,其中包含其他注释的ID。这就像一个嵌套的树结构,但文档是单独存储在MongoDB中的。
当从服务器发送文档时,我希望它们保持独立的文档,并且只包含对其他注释的ID引用,而不是注释本身。换句话说,对象应该看起来像服务器上的对象。
如何在单个查询中请求注释树,但将注释保留为单独的文档?
我知道,当您想要查询嵌套文档时,填充会很有用。我对populate的问题是,您收到的是一个大的嵌套对象,而不是单个文档。
this.populate({ path: 'replies' })
输出:
{ _id: "61acd4474bbaa88d12c38199",
textContent: "This comment has 2 replies",
replies: [
{ _id: "61acd57fe06fed9e70462139",
textContent: "This comment has 0 replies",
replies: []
},
{ _id: "61acd57fe06fed9e7046213a",
textContent: "This comment has 0 replies",
replies: []
}
]
}
所需输出:
[
{ _id: "61acd4474bbaa88d12c38199",
textContent: "This comment has 2 replies",
replies: [ "61acd57fe06fed9e70462139", "61acd57fe06fed9e7046213a" ]
},
{ _id: "61acd57fe06fed9e70462139",
textContent: "This comment has 0 replies",
replies: [ ]
},
{ _id: "61acd57fe06fed9e7046213a",
textContent: "This comment has 0 replies",
replies: [ ]
}
]