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

173
Visualizações
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 Respostas
Responde à pergunta

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