Home > Net >  map() returns undefined error after Mongoose populate
map() returns undefined error after Mongoose populate

Time:11-10

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.

CodePudding user response:

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

will return an array of viewedBy values. so array 'a' doesnt contain the full objects. it contains an array of viewedBy elements. also, please take a look at the functionality of the .map() function.

CodePudding user response:

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

const data = [
   {
      id: 123,
      email: "[email protected]"
   },
   {
      id: 456,
      email: "[email protected]"
   }
];

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

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

  • Related