简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM