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

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

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 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