如何获取内部数组的特定值以及Mongoose

时间:2015-11-19 12:18:31

标签: node.js mongodb mongoose mean

我有一个如下所示的集合

[
    {
        "_id":"564d747ce27a66cd5aa6fdf2",
        "Name":"Person1",
        "Role":[
            {
                "_id":"564d7253e27a66cd5aa6fdee",
                "RoleName":"AAA",
                "Rel":[
                    {
                        "_id":"564d728be27a66cd5aa6fdf0",
                        "Name":"Lead"
                    }
                ]
            },
            {
                "_id":"564d7253e27a66cd5aa6fdef",
                "RoleName":"BBB",
                "Rel":[
                    {
                        "_id":"564d728be27a66cd5aa6fdf0",
                        "Name":"Member"
                    }
                ]
            }
        ]
    },
    {
        "_id":"564d747ce27a66cd5aa6fdf2",
        "Name":"Person2",
        "Role":[
            {
                "_id":"564d7253e27a66cd5aa6fdee",
                "RoleName":"AAA",
                "Rel":[
                    {
                        "_id":"564d728be27a66cd5aa6fdf0",
                        "Name":"Lead"
                    }
                ]
            }
        ]
    }
]

现在,我想检查一个角色ID并获取其相关的'Rel'以及名称,如下所示:

[
    {
        "_id":"564d747ce27a66cd5aa6fdf2",
        "Name":"Person1",
        "Role":[
            {
                "_id":"564d7253e27a66cd5aa6fdee",
                "RoleName":"AAA",
                "Rel":[
                    {
                        "_id":"564d728be27a66cd5aa6fdf0",
                        "Name":"Lead"
                    }
                ]
            }
        ]
    },
    {...}
]

我使用Mongoose来获取数据,如下所示:

exports.findone = function(req, res) {
    var id = req.params.id;
    model1.find({'Role._id': id}).select('Name Role').exec(function(err, results) {
         res.send(results));    
  });
};

这里,当我将角色ID作为输入发送时,它会获取具有所提及的角色ID的人。但是在“角色”节点中,我获得了与之相关的所有角色。以下是我为上述查询获得的输出。

[
    {
        "_id":"564d747ce27a66cd5aa6fdf2",
        "Name":"Person1",
        "Role":[
            {
                "_id":"564d7253e27a66cd5aa6fdee",
                "RoleName":"AAA",
                "Rel":[
                    {
                        "_id":"564d728be27a66cd5aa6fdf0",
                        "Name":"Lead"
                    }
                ]
            },
            {
                "_id":"564d7253e27a66cd5aa6fdef",
                "RoleName":"BBB",
                "Rel":[
                    {
                        "_id":"564d728be27a66cd5aa6fdf0",
                        "Name":"Member"
                    }
                ]
            }
        ]
    }
]

我想获得特定角色而不是所有角色都要显示。你能帮我完成这件事......

1 个答案:

答案 0 :(得分:1)

您可以将v_norm = v.normalized()操作与select一起使用,以便只显示您想要的角色,如MongoDB docs中所述。

您的数据提取看起来像这样:

$elemMatch