使用地图在 Sequelize 中创建一个新的普通对象

using map to create a new plain object in Sequelize

我正在尝试映射我的对话数组以使用 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);

});

当我尝试此代码时,我总是无法读取 属性 未定义的地图。

问题在于您正在查询 Conversations,然后直接将它们视为 Posts。实际上,您查询了 Conversations,然后包含了与每个 Conversation 有关系的 Posts,spo 它们将出现在返回的数据中,但嵌套在每个对象中。

// 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;
  ...
}

我希望这可以帮助您了解代码中发生的事情!