首页 > 解决方案 > Node.js、multer、express、sequelize、Postgres

问题描述

我目前正在尝试将图像存储在我的数据库中。

这是我的帖子模型:-

id: {
field: "PostId",
type: Sequelize.INTEGER,
primaryKey: true,
},
title: {
type: Sequelize.STRING,
},
images: {
type: Sequelize.STRING
}

这是我的发帖请求:-

router.post(
"/",
 [
 upload.array("images", config.get("maxImageCount")),
 imageResize,
 ],
 async (req, res) => {
const paths = await req.files.map((file) => ({ fileName: file.filename }));
Posts.create({
  title: req.body.title,
  images: JSON.stringify(paths),
}).then(
  () => {
    res.status(201).send({
      msg: "upload successful",
    });
  },
  (validation) => {
    res.status(422).json({
      errors: validation.errors.map((error) => {
        return {
          fieldName: error.path,
          message: error.message,
        };
      }),
    });});});

我现在正在使用 multer 将我的图像存储在磁盘上,并使用锐利来调整我的图像大小。

我的问题是当我去 localhost/posts 时,图像是这样的:-

`"images":"[{\"fileName\":\"95aa17.‌​png-2020-11-08T14:24‌​:33.221Z\"},{\"fileN‌​ame\":\"fwfe.pn‌​g-2020-11-08T14:24:3‌​3.268Z\"}]"`

当它应该看起来像这样时:-

`"images":"[{"fileName":"95aa17.‌​png-2020-11-08T14:24‌​:33.221Z"},{"fileN‌​ame":"fwfe.pn‌​g-2020-11-08T14:24:3‌​3.268Z"}]"`

经过数小时的研究,我发现为了最佳实践,我不应该在数组上使用 JSON.stringify。

我应该如何解决这个问题?

标签: node.jspostgresqlsequelize.jsmulter

解决方案


我设法解决了这个问题。这是解决方案:

router.post(
"/",
[
upload.array("images", config.get("maxImageCount")),
imageResize,
],
async (req, res) => {
const paths = await req.files.map((file) => ({ fileName: file.filename }));
Posts.create({
title: req.body.title,
images: paths.map((x) => ({ images: x.fileName }));
}).then(
() => {
res.status(201).send({
  msg: "upload successful",
});
},
(validation) => {
res.status(422).json({
  errors: validation.errors.map((error) => {
    return {
      fieldName: error.path,
      message: error.message,
    };
  }),
});});});

我将图像作为文件名存储在数据库中。


推荐阅读