nodejs, postgres, sequelize - instead of getting the filename, trying to get full path

*爱你&永不变心* 提交于 2020-12-13 03:39:44

问题


After storing my images separately as strings in postgres. when i go to the route, images looks like this (the response i am currently getting)

 "images":"image1.png-2020-11-11T13:15:55.692Z"

i am trying to get it like this

"images":["url":"image1.png-2020-11-11T13:15:55.692Z_full","thumbnailUrl":"image1.png-2020- 
11-11T13:15:55.692Z_thumb"]

Here is my get request

router.get("/", (req, res) => 
 Post.findAll({
order: [["createdAt", "DESC"]],
include: { model: Post_Image, attributes: ["id", "images"] },
 }).then((posts) => {
const baseUrl = config.get("assetsBaseUrl");

for (let post of posts) {

  const postImages = post.Post_Images;

  const img = postImages.map((post) => post.dataValues);

  const imgFileName = img.map((post) => post.images);

  const IMAGES = imgFileName.map((image) => ({
    url: `${baseUrl}${image}_full.jpg`,
    thumbnailUrl: `${baseUrl}${image}_thumb.jpg`,
  }));
    console.log(IMAGES)
}

res.send(posts);
 });
});

when i do console.log(IMAGES), here is my response

[
  {
   url: 'http://LOCALHOST:PORT/assets/image1.png-2020-11-11T13:15:55.692Z_full.jpg',
   thumbnailUrl: 'http://LOCALHOST:PORT/assets/image1.png-2020-11- 
 11T13:15:55.692Z_thumb.jpg'
  }

]

i was trying to do

return{
...post,
images:IMAGES}

but it did not work.

Here is the response i am expecting to get from my get request when i go to the route:

  "images": [{"url":"http://192.168.1.103:9000/assets/jacket1_full.jpg","thumbnailUrl" :"http://192.168.1.103:9000/assets/jacket1_thumb.jpg"}]

回答1:


You should turn Post model instances into plain objects and add images prop to each of them:

const plainPosts = posts.map(x => x.get({ plain: true }))
const resultPosts = []
for (const post of plainPosts) {
  const { Post_Images, ...postAttributes } = post
  const IMAGES = Post_Images.map((postImage) => ({
    url: `${baseUrl}${postImage.images}_full.jpg`,
    thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
  }));
  console.log(IMAGES)
  resultPosts.push({
    ...postAttributes,
    images: IMAGES
  })
}

res.send(resultPosts);

if you get a single post only then this should look like:

const plainPost = post.get({ plain: true })
const { Post_Images, ...postAttributes } = plainPost
const IMAGES = Post_Images.map((postImage) => ({
  url: `${baseUrl}${postImage.images}_full.jpg`,
  thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));
console.log(IMAGES)

res.send({
    ...postAttributes,
    images: IMAGES
  });


来源:https://stackoverflow.com/questions/64788409/nodejs-postgres-sequelize-instead-of-getting-the-filename-trying-to-get-ful

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