Paras Dhawan
Paras Dhawan

Reputation: 374

Mongoose how to implement nested queries

My db schema is

Collection - Question

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

Collection - Answers

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

I created an API to get all the Questions and for each "_Id" i need to access the collection- Answers and retrieve the answer corresponding to that questionId. How can i achieve this? .

Upvotes: 1

Views: 348

Answers (1)

Tarush Arora
Tarush Arora

Reputation: 576

I would recommend you to embed the answer in the question collection.

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

Schema:-

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

Or:-

if only userIds will be added in future to the answers, then you can make answers an Object instead of an array of objects, that depends on your application logic.

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

Now you do not need to run two queries for retrieving both questions and answers for a particular question. If you need to retrieve data in custom format, you have to use MongoDB Aggregation framework

If you want to know more about the embedded data model design in MongoDB, please refer to this documentation

Upvotes: 2

Related Questions