Mongoose如何实现嵌套查询
我的数据库模式是
collections – 问题
{ "_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 ] } ] }
我创build了一个API来获取所有的问题,并为每个“_Id”我需要访问集合 – 答案和检索对应于该questionId的答案。 我怎么能做到这一点? 。
我会build议你在问题集合中embedded答案。
{ "_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
,那么您可以将Object
而不是对象数组作为answers
,这取决于您的应用程序逻辑。
{ "type" : Number, "question" : String, "options" : [String], "answers": { "userId":[Number] } }
现在,您不需要运行两个查询来检索特定问题的questions
和answers
。 如果您需要以自定义格式检索数据,则必须使用MongoDB Aggregation框架
如果您想了解更多有关MongoDB中的embedded式数据模型devise的信息,请参阅本文档