using map to create a new plain object in Sequelize

此生再无相见时 提交于 2020-12-15 03:45:50

问题


i am trying to map my conversation array to create a new object with url and thumbnail url instead of the image file name.

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);

});

when i try this code i keep getting cannot read property map of undefined.


回答1:


The issue lies in the fact that you are making a query for Conversations and then treating them directly like they are Posts. In reality you have queried Conversations and then included Posts that have a relationship with each Conversation, spo they will be present on the returned data, but nested in each object.

// Conversations query
const conversations = await Conversation.findAll({
  include: [
    {
      Post,
      attributes:["id","title","userId"],
      include: [
        { model: User, attributes: ["id", "name", "email"] },
        { model: Post_Image, attributes: ["id", "images"] },
      ],
    }
  ],
});

// Conversations now look something like
{
  ...someValues,
  Post: Post (This is the object that contains the Post_Images) | null;
}[]

...

const plainConversations = conversations.map(x=>x.get({ plain: true }));

// Previously you were referring to the conversations as posts, 
// which was generating confusion
for (conversation of plainConversations) {
  { Post: { Post_Images }, ...ignore } = conversation;
  ...
}

I hope this helps you understand what's going on in your code!



来源:https://stackoverflow.com/questions/65194232/using-map-to-create-a-new-plain-object-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!