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

171
Vistas
How to map an array of objectIDs and get objects with those ids?

So basically I have a collection that holds ids which reference objects in another schema.

If I have an array which holds these ids, how can I map through the array and get the object associated with that id?

This is what I have so far but the response is just empty objects:

// this gives me an array of all the itemIds that a buyer has bought.
const prevPurchases = await Sales.find({ buyerId }).select(["itemId"]);

const item = prevPurchases.map(async (e) => {
   try {
      const item = await Item.findById(e.itemId).select(["image", "name"]);
      return item;
   } catch (e) {
      return null;
   }
});

await Promise.all(item);

return res.status(200).json({ item }); // just returns "{}, {}, {}, etc" 

How can I fix this so that the objects contain the image and the name of item as I specified in the select. Thank you!

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

0

You can try collecting item ids in array and use $in operator to select all the items by single find query,

try {

  const prevPurchases = await Sales.find({ buyerId }).select(["itemId"]);

  let items = [];
  if (prevPurchases.length) { 
    items = await Item.find({ 
      _id: { $in: prevPurchases.map((e) => e.itemId) } 
    }).select(["image", "name"]);
  }

  return res.status(200).json({ items });

} catch (e) {
  return null;
}
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