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

91
Vistas
Mongoose Lookup with foreign key as array

I have a questions collection with _id and name and other fields(..), and a tests collection with _id, name and array of questions.

I'm trying to get all the questions with their fields and adding a field "usedIn" which counts the number of tests that the specific questions is present in.

    questions = await Question.aggregate([
                /*{
                    "$match": {
                        params
                    }
                },*/
                {

                    "$lookup": {
                        "from": "tests",
                        "let": {"questionId": "$_id"},
                        pipeline: [
                            {
                                "$match": {
                                    "$expr": {
                                        "$in": ["$$questionId", "$questions"],
                                    },
                                },
                            },
                        ],
                        as: "tests"
                    }
                },

                {
                    "$addFields": {
                        "usedIn": {
                            "$size": "tests"
                        }
                    }
                },
                {
                    "$project": fieldsObject
                },

            ])

This code is giving me this error:

Error: Failed to optimize pipeline :: caused by :: The argument to $size must be an array, but was of type: string

What Am I doing wrong ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do it like this:

db.questions.aggregate([
  {
    "$lookup": {
      "from": "tests",
      "localField": "_id",
      "foreignField": "questions",
      "as": "usedIn"
    }
  },
  {
    "$project": {
      "usedIn": {
        "$size": "$usedIn"
      },
      "name": 1
    }
  }
])

Working example

about 4 years ago · Juan Pablo Isaza 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