node.js - 使用 map 在 Sequelize 中创建一个新的普通对象

标签 node.js sequelize.js

我正在尝试映射我的对话数组以创建一个带有 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 ,然后包含与每个 Posts 有关系的 Conversation ,它们将出现在返回的数据中,但嵌套在每个对象中。

// 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;
  ...
}
我希望这可以帮助您了解代码中发生的事情!

关于node.js - 使用 map 在 Sequelize 中创建一个新的普通对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65194232/

相关文章:

javascript - 如何使用 Sequelize - Mocha Node 和 javascript 连接到数据库

javascript - 在 Ubuntu 11.10 上编译 Node 0.4.7?

node.js - 零停机升级nodejs websocket Web应用程序

node.js - 序列化查询 where or 失败并出现空错误

Sequelize.js 模型具有 madeFrom 和 madeTo 属性。如何获得特定年份生产的所有车型?

node.js - Sequelize : Adding a day to the date doesn't work

javascript - 将对象数组的值拼接到句子中

node.js - nodejs - 从地理服务器返回文本的快速请求形状 zip

sequelize.js - Sequelize : How to query with where on association primaryKey without creating join

mysql - 如何防止用户更改电脑时间并修改mysql中插入行的时间戳