节点js两次收集结果

时间:2019-02-08 10:34:35

标签: node.js mongodb mongoid node-modules google-api-nodejs-client

我有两个表,一个是项目,另一个是里程碑,我需要mongodb查询如何获取以下结果:

{
    "result": "success",
    "data": {
        "projects": [{
            "projectName": "p1",
            "projectId": "1dewdadas",
            "milestones": [{
                "milestoneId": "a1",
                "milestoneName": "Create UI"
            },
            {
                "milestoneId": "a3",
                "milestoneName": "Create DB and API "
            },
            {
                "milestoneId": "a2",
                "milestoneName": "Testing"
            }],
            "people": [{
                "empId": "1",
                "name": "shashi"
            },
            {
                "empId": "2",
                "name": "ganesh"
            },
            {
                "empId": "3",
                "name": "gaurav"
            }]
        },
        {
            "projectName": "p2",
            "projectId": "231wda231",
            "milestones": [{
                "milestoneId": "a1",
                "milestoneName": "milestone 6"
            },
            {
                "milestoneId": "a3",
                "milestoneName": "milestone 7"
            },
            {
                "milestoneId": "a2",
                "milestoneName": "milestone 8"
            }],
            "people": [{
                "empId": "1",
                "name": "user1"
            },
            {
                "empId": "2",
                "name": "user2"
            },
            {
                "empId": "3",
                "name": "user3"
            }]
        },
        {
            "projectName": "p3",
            "projectId": "dfsdfsdf",
            "milestones": [{
                "milestoneId": "a1",
                "milestoneName": "milestone 1"
            },
            {
                "milestoneId": "a3",
                "milestoneName": "milestone 2"
            },
            {
                "milestoneId": "a2",
                "milestoneName": "milestone 3"
            }],
            "people": [{
                "empId": "1",
                "name": "user 4"
            },
            {
                "empId": "2",
                "name": "user 5"
            },
            {
                "empId": "3",
                "name": "user 6"
            }]
        }]
    }
}

1 个答案:

答案 0 :(得分:1)

我使用mongoose进行mongodb连接。

您可以这样定义项目模型

const projectSchema = new mongoose.Schema({
projectName: {
    type: String,
    required: true
},
projectId:{
    type: String,
    required: true
},
milestones:[{
    type: mongoose.Types.ObjectId,
    ref: 'milestones'
}],
people:[{
    type: mongoose.Types.ObjectId,
    ref: 'people'
}]

});

const Project = mongoose.model('projects', projectSchema);

和用途

projects = Project.find({}).populate('milestones','people);