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

349
Vistas
map() returns undefined error after Mongoose populate
const form = await Form.findOne({ _id: res._id }).populate({
   path: "activity.viewedBy",
   model: User,
});

const a = await form.activity.map((a) => a.viewedBy);

console.log(a.map((e) => e.email));

"Cannot read property 'email' of undefined"

Why? a is an array, full of objects, like this:

[
   {
      id: 123,
      email: example@email.com
   },
   {
      id: 456,
      email: nice@email.com
   }
]

Edit, sharing the whole async function:

const viewForm = async (req, res) => {
    const form = await Form.findOne({ _id: res._id }).populate({
       path: "activity.viewedBy",
       model: User,
    });
    
    const a = await form.activity.map((a) => a.viewedBy);
    
    console.log(a.map((e) => e.email));

    await Form.updateOne(
        { _id: res._id },
        {
            $push: {
                activity: {
                    viewedBy: res.user,
                    date: new Date(),
                },
            },
        }
    );

    return {
        statusCode: 200,
        body: JSON.stringify(`Form viewed.`),
    };
};

Edit2:

There was an undefined in the array, among the objects, I didn't notice that... That's why I was getting the undefined.

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

0

a probably has a different structure than you think (try console.log(a)), just proving:

const data = [
   {
      id: 123,
      email: "example@email.com"
   },
   {
      id: 456,
      email: "nice@email.com"
   }
];

const result = data.map((a) => a.email);

console.log(result);

Also, giving your variables meaningful names can help to prevent mistakes.

about 4 years ago · Juan Pablo Isaza Denunciar

0

await form.activity.map((a) => a.viewedBy);

will return an array of viewedBy values. So the array a doesn't contain the full objects. Instead, it contains an array of viewedBy elements. Also, please take a look at the functionality of the map() function.

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