Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

348
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!