【发布时间】:2021-08-23 03:54:20
【问题描述】:
我有三个用 mongodb 编写的文档。它主要类似于文件夹和文件结构。我正在尝试通过输入类别 ID 来搜索文件类别。
如果有任何文件与类别 id 匹配,我需要将父文件夹文档中的这些文件作为嵌入数组列出来作为响应。
文档文件夹
[
{
_id: "5f7763103a4af84960f86ae6",
folderName: "abcd"
},
{
_id: "5f7763103a4af84960f86ae7",
folderName: "qwerty"
},
{
_id: "5f7763103a4af84960f86ae8",
folderName: "asdfgh"
},
]
文档文件
[
{
_id: "1c7763103a4af84960f86aa5",
fileName: "test file 1",
folderId: "5f7763103a4af84960f86ae7",
categoryId: "6b7763103a4af84960f86ae2"
},
{
_id: "1c7763103a4af84960f86aa6",
fileName: "test file 2",
folderId: "5f7763103a4af84960f86ae7",
categoryId: "6b7763103a4af84960f86ae2"
},
{
_id: "1c7763103a4af84960f86aa7",
fileName: "test file 3",
folderId: "5f7763103a4af84960f86ae6",
categoryId: "6b7763103a4af84960f86ae2"
},
]
文档类别
[
{
_id: "6b7763103a4af84960f86ae1",
categoryName: "misc"
},
{
_id: "6b7763103a4af84960f86ae2",
categoryName: "images"
},
{
_id: "6b7763103a4af84960f86ae3",
categoryName: "other"
},
]
当我在 files 文档中按 categoryId 搜索时,我需要将所有匹配的文件分组到与父文件夹名称分组的数组中。
我期待如下结果
{
folder: {
_id: "5f7763103a4af84960f86ae7",
folderName: "qwerty",
files: [
{
_id: "1c7763103a4af84960f86aa5",
fileName: "test file 1",
folderId: "5f7763103a4af84960f86ae7",
categoryId: "6b7763103a4af84960f86ae2"
},
{
_id: "1c7763103a4af84960f86aa6",
fileName: "test file 2",
folderId: "5f7763103a4af84960f86ae7",
categoryId: "6b7763103a4af84960f86ae2"
},
{
_id: "1c7763103a4af84960f86aa7",
fileName: "test file 3",
folderId: "5f7763103a4af84960f86ae6",
categoryId: "6b7763103a4af84960f86ae2"
},
]
}
}
【问题讨论】:
标签: javascript node.js mongodb mongoose mongodb-query