【发布时间】:2021-03-19 11:56:31
【问题描述】:
我正在尝试映射我的对话数组以使用 url 和缩略图 url 而不是图像文件名创建一个新对象。
router.get('/', auth, async (req, res) => {
const conversations = await Conversation.findAll({
include: [
// {
// model: Message,
// where: {
// [Op.or]: [
// { senderId: req.user.id },
// { receiverId: req.user.id },
// ],
// },
// required: true, // RIGHT JOIN
// },
{
Post,
attributes:["id","title","userId"],
include: [
{ model: User, attributes: ["id", "name", "email"] },
{ model: Post_Image, attributes: ["id", "images"] },
],
}
],
});
if (!conversations) return res.status(404).send();
const baseUrl = config.get("assetsBaseUrl");
const plainConversations = conversations.map(x=>x.get({ plain: true }));
const resultPosts = [];
for (const post of plainConversations) {
const { Post_Images, ...postAttributes } = post;
const IMAGES = Post_Images.map((postImage) => ({
url: `${baseUrl}${postImage.images}_full.jpg`,
thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));
resultPosts.push({ ...postAttributes, images: IMAGES });
}
res.send(resultPosts);
});
当我尝试这段代码时,我不断收到无法读取未定义的属性映射。
【问题讨论】:
-
最可能的问题是以下行
const { Post_Images, ...postAttributes } = post;,您能否在下一行的地图之前记录Post_Images的值? -
@CoryHarper 我未定义
-
对,所以这告诉您
Post_Images不是您正在迭代的post的属性。尝试在同一行记录post,看看它是什么样子的。 -
将
const { Post_Images, ...postAttributes } = post;更改为const { Post: { Post_Images }, ...postAttributes } = post; -
我会留下更详细的完整答案。
标签: node.js sequelize.js