Básicamente, tengo una colección que contiene identificadores que hacen referencia a objetos en otro esquema.
Si tengo una matriz que contiene estas identificaciones, ¿cómo puedo mapear a través de la matriz y obtener el objeto asociado con esa identificación?
Esto es lo que tengo hasta ahora, pero la respuesta son solo objetos vacíos:
// 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" ¿Cómo puedo arreglar esto para que los objetos contengan la imagen y el nombre del elemento como lo especifiqué en el select . ¡Gracias!
Puede intentar recopilar ID de elementos en una matriz y usar el operador $in para seleccionar todos los elementos mediante una consulta de búsqueda única,
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; }