Mongoose如何实现嵌套查询

时间:2017-01-31 15:01:50

标签: node.js mongodb mongoose

我的数据库架构是

收藏 - 问题

 {
        "_id" : ObjectId("588f79d7535415ceb7a026bd"),
        "type" : 1,
        "question" : "Who is the best bastman from the following:",
        "options" : [ 
            "Sachin Tendulkar", 
            "Rahul Dravid"
        ]
    }

收藏 - 答案

{
    "questionId" : "588f79d7535415ceb7a026bd",
    "answers" : [ 
        {
            "userId" : [ 
                102, 
                101, 
                105
            ]
        }
    ]
}

我创建了一个API以获取所有问题,并且对于每个“_Id”我需要访问集合 - 答案并检索与该questionId相对应的答案。 我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

我建议你在问题集中嵌入答案。

{
    "_id" : ObjectId("588f79d7535415ceb7a026bd"),
    "type" : 1, 
    "question" : "Who is the best bastman from the following:",
    "options" : [ 
        "Sachin Tendulkar", 
        "Rahul Dravid"
    ],
    "answers": [{
         "userId":[102,101,105]             
     }]
}

架构: -

{
    "type" : Number, 
    "question" : String,
    "options" : [String],
    "answers": [{
         "userId":[Number]             
     }]
}

或者: -

如果将来userIds只添加answers,那么您可以answers Object而不是对象数组,这取决于您的应用逻辑。

{
    "type" : Number, 
    "question" : String,
    "options" : [String],
    "answers": {
         "userId":[Number]             
     }
}

现在,您无需针对特定问题运行两个查询来检索questionsanswers。 如果您需要以自定义格式检索数据,则必须使用MongoDB Aggregation framework

如果您想了解有关MongoDB中嵌入式数据模型设计的更多信息,请参阅此documentation

相关问题