Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
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? .

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda