Mongoose how to implement nested queries

391
January 31, 2017, at 9:17 PM

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? .

Answer 1

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

Rent Charter Buses Company
READ ALSO
Main connection with node-mssql

Main connection with node-mssql

I'm using node module "node-mssql" to connect a SQL Server, I'm not sure if I'm doing it right

452
Can´t set headers after they are send checking for email and name

Can´t set headers after they are send checking for email and name

in my projet i want to build a store tha has some products, to do that i defined 2 schemas a store(loja) schema and a product schema(produto), i want to post the data from reqbody and check it with postman, i want to check if the email and the name already...

306
How to identify results in Promise.all()

How to identify results in Promise.all()

I am create a module that is executing tasks based on a config it receivesThese tasks are asynchronous and are returning a promise

378
Different variable name case convention in one application

Different variable name case convention in one application

This is a really trivial problemI am just curious on how to deal with this in a "professional" manner

373