[英]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: a
是一个数组,充满了对象,像这样:
[
{
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:编辑2:
There was an undefined
in the array, among the objects, I didn't notice that... That's why I was getting the undefined.数组中有一个
undefined
,在对象中,我没有注意到......这就是我得到 undefined 的原因。
a
probably has a different structure than you think (try console.log(a)
), just proving: a
可能具有与您想象的不同的结构(尝试console.log(a)
),只是证明:
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.将返回一个由
viewedBy
值组成的数组。 So the array a
doesn't contain the full objects.所以数组
a
不包含完整的对象。 Instead, it contains an array of viewedBy
elements.相反,它包含一个由
viewedBy
元素组成的数组。 Also, please take a look at the functionality of the map()
function.另外,请看一下
map()
函数的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.