我的群组收藏是这样的

[
{
    "_id": "55fdbaa7457aa1b9bd7f7cf7",
    "group_name":"Tango Charli",
    "group_desc":"This group is for chatting",
    "group_admins": [
        {
            "_id": "55ff7fca8d3f6607114dc57d",
            "user_id": "55ff7fca8d3f7607114dc57e",
            "name": "James",
        },
        {
            "_id": "55ff7fca8d3f6607114dc57d",
            "user_id": "55ff7fca8d3f7607114dc57e",
            "name": "James",
        }
    ]
},

{
    "_id": "55fdbaa7457aa1b9bd7f8de8",
    "group_name":"Love zone",
    "group_desc":"This group is for making love and chatting",
    "group_admins": [
        {
            "_id": "55ff7fca8d3f6607114dc57d",
            "user_id": "55ff7fca8d3f7607114dc57e",
            "name": "Mike",
        },
        {
            "_id": "55ff7fca8d3f6607114dc57d",
            "user_id": "55ff7fca8d3f7607114dc57e",
            "name": "alice",
        }
    ]
},

]


我想列出特定群组的群组管理员

为此,我正在使用以下查询

groupModel.find({_id:55fdbaa7457aa1b9bd7f7cf7},'group_admins -_id',function(err,groupDetails){

    if(err)
    {
        res.json({
            "isError":true,
            "error":{
                "status":1042,
                "message":err
            }
        });
    }
    else
    {
        res.json(groupDetails);
    }
}
);//end of groupModel find


它给出以下输出

[
    {
        "group_admins": [
            {
                "_id": "55ff7fca8d3f6607114dc57d",
                "user_id": "55ff7fca8d3f7607114dc57e",
                "name": "James",
            },
            {
                "_id": "55ff7fca8d3f6607114dc57d",
                "user_id": "55ff7fca8d3f7607114dc57e",
                "name": "James",
            }
        ]
    }
]


但我想以以下格式输出

[
{
    "_id": "55ff7fca8d3f6607114dc57d",
    "user_id": "55ff7fca8d3f7607114dc57e",
    "name": "James",
},
{
    "_id": "55ff7fca8d3f6607114dc57d",
    "user_id": "55ff7fca8d3f7607114dc57e",
    "name": "James",
}
]


我该怎么做,请提出建议

最佳答案

如果您只是在寻找一条记录,则应使用findOne()而不是find()。然后访问它的group_admins属性。即

groupModel.findOne({_id:55fdbaa7457aa1b9bd7f7cf7},'group_admins -_id',function(err,groupDetails){
    res.json(groupDetails['group_admins']);
});

关于node.js - 仅在 Mongoose 中选择子文档数组列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32688059/

10-11 10:44