anacronw / multer-s3

multer storage engine for amazon s3
MIT License
660 stars 190 forks source link

Store the files location in mongoDB #125

Closed benbagley closed 4 years ago

benbagley commented 4 years ago

Is this possible?

Here is my configuration:

const aws = require("aws-sdk");
const multerS3 = require("multer-s3");
const multer = require("multer");

aws.config.update({
  secretAccessKey: process.env.AWS_SECRET_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY,
  region: "us-east-2"
});

s3 = new aws.S3();

const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: process.env.AWS_BUCKET,
    contentType: multerS3.AUTO_CONTENT_TYPE,
    acl: "public-read",
    key: function(req, file, cb) {
      cb(null, Date.now() + file.originalname);
    }
  })
});

controller

/* POST create a collection */
module.exports.createCollection = [
  ...validations,
  (req, res) => {
    // Get validation errors from the request
    const errors = validationResult(req);
    // Return the errors
    if (!errors.isEmpty()) {
      return res.status(422).json({ error: errors.array() });
    }

    Collections.findOne({ _id: req.body.id }).then(function(collection) {
      Collections.create({
        title: req.body.title,
        description: req.body.description,
        reference: req.body.reference,
        images: req.files.map(({ originalname, mimetype }) => ({
          filename: originalname,
          mimetype
        })),
        price: req.body.price,
        year: req.body.year,
        categoryName: req.body.categoryName,
        sold: req.body.sold
      })
        .then(function(collection) {
          res.status(201).json(collection);
        })
        .catch(function(error) {
          console.error(error);
          res.status(500).send(error);
        });
    });
  }
];

schema

images: [{ filename: String, mimetype: String }],

I want to be able to save an array of images for each collection so I can render them out.

Files are being uploaded to s3 but I need to be able to get the files for that collection, this is how there being stored