首页 > 解决方案 > 如何在 mongoose 的嵌套对象中查询嵌套数组的 id?

问题描述

这是我的诗句架构

{
    "verses": [
        {
            "id": "111",
            "happy": [
                {
                    "id": "112",
                    "versePath": "Proverbs 15:13",
                    "content": "A glad heart makes a cheerful face, but by sorrow of heart the spirit is crushed"
                }
            ],
            sad: [
                {
                    id: 113,
                    versePath: "text",
                    content: "text"
                }
            ]
        }
    ]
}

我想查询以通过 id 查找每个对象。我尝试使用 elemMatch 执行此操作,但没有成功。

const verse = await Verses
    .find({ _id: id })
    .elemMatch("empathy", { _id: req.params.id, });

我也尝试过使用聚合,但它也不起作用。

const verse = await Verses.aggregate([
    { "$unwind": "$verses" },
    { "$match": { "verses._id": req.params.id } }
])

不起作用,我的意思是两种尝试都返回一个空数组或整个 json 对象。我希望我的结果返回每个嵌套对象 id: 112, versePath

标签: javascriptnode.jsmongodbmongooseschema

解决方案


推荐阅读