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

121
Visualizações
Mongoose Populate Null Reference

I have two simple models defined in Mongoose, composed of two schema Client and City, I have the property city defined in Client as a ObjectId, ref: 'City', so far so good.

If I query for a client and want also to filter by the 'province' property of City, I do this:

const client = await Client
    .find({ name: "Gérard" })
    .populate([{
        path: 'city',
        model: City,
        match: { province: 'BA' }
    }]);

And the output is just fine:

{
  "id": "627264e3ec261a883d42ead9",
  "name": "Gérard",
  "email": "gerard@depardieu.fr",
  "date": "1948-12-27",
  "active": true,
  "city": {
    "id": "627264e3ec261a883d42ead1",
    "name": "Buenos Aires",
    "province": "BA"
  }
}

Howerver, if I input a province code of a nonexistent city:

const client = await Client
    .find({ name: "Gérard" })
    .populate([{
        path: 'city',
        model: City,
        match: { province: 'CA' }
    }]);

It would return me that:

{
  "id": "627264e3ec261a883d42ead9",
  "name": "Gérard",
  "email": "gerard@depardieu.fr",
  "date": "1948-12-27",
  "active": true,
  "city": null
}

I don't want in this particular scenario, any instance of Client to be returned, and I don't know how to avoid this behavior with Mongoose, a behavior I never had to worry about with Spring Data for instance.

Any tips for me?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I solved it myself, I had to go a little lower level with Mongoose and use aggregates and lookups.

const client = await Client.aggregate([
  { 
    $match: { name: "Gérard" } 
  },
  {
    $lookup: {
      from: City.collection.name,
      pipeline: [
        {
          $match: {
            province: 'BA'
          }
        }
      ], as: "city"
    }
  },
  {
     $unwind: "$city"
  },
  {
     $match: {
       city: { $ne: [] }
     }
   }
]);

Expected result:

{
  "id": "627264e3ec261a883d42ead9",
  "name": "Gérard",
  "email": "gerard@depardieu.fr",
  "date": "1948-12-27",
  "active": true,
  "city": {
    "id": "627264e3ec261a883d42ead1",
    "name": "Buenos Aires",
    "province": "BA"
  }
}

Witch is ok, client name "Gérard" lives in "Buenos Aires", situated in province "BA".

On the other hand:

const client = await Client.aggregate([
  { 
    $match: { name: "Gérard" } 
  },
  {
    $lookup: {
      from: City.collection.name,
      pipeline: [
        {
          $match: {
            province: 'CA'
          }
        }
      ], as: "city"
    }
  },
  {
     $unwind: "$city"
  },
  {
     $match: {
       city: { $ne: [] }
     }
   }
]);

Returns nothing, once the city of "Buenos Aires" is not located in province "CA".

Notice here the last parameter (as an object) the array passed to Client.aggregate() receives:

{
  $match: {
    city: { $ne: [] }
  }
}

This tells MongoDB that in order to return data city must be not equal to an empty array.

And with that the issue is solved.

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