Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

307
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda