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

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

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

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

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