我正在尝试映射我的对话数组以创建一个带有 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/