Reputation: 238
I'm uploading images from a form to my S3 bucket. When the form is submitted, it creates a new mongoDB object. I'm using key: function (req, file, cb) {cb(null, Date.now().toString())},
to give the uploads unique names. My issue is, when I'm saving the new mongoDB object, I'm not sure how to reference the unique S3 key.
I admit this might be a dumb question, but I'm not very experienced with mongoDB/mongoose and this is my first time ever working with S3.
I would greatly appreciate any advice or recommendations
// productController.js
// if errors on form
else {
let product = new Product({
business: req.body.businessName,
productName: req.body.productName,
category: req.body.productCategory,
price: req.body.productPrice,
description: req.body.productDescription,
website: req.body.website,
imageURL: "https://mybucket.s3-us-west-2.amazonaws.com/" + '???'
});
product.save(function (err) {
if (err) {
console.log(err)
return next(err);
}
res.redirect("/list-product");
});
}
to upload my images im using this:
// uploadController.js
const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");
require("dotenv").config();
aws.config.update({
secretAccessKey: process.env.SECRETACCESSKEY,
accessKeyId: process.env.ACCESSKEYID,
region: "us-west-2",
});
const s3 = new aws.S3();
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
cb(null, true);
} else {
cb(new Error("Invalid format, only JPG and PNG"), false);
}
};
const upload = multer({
fileFilter: fileFilter,
storage: multerS3({
s3: s3,
bucket: "mybucket",
acl: "public-read",
metadata: function (req, file, cb) {
cb(null, { fieldName: file.fieldname });
},
key: function (req, file, cb) {
console.log(file);
cb(null, Date.now().toString());
},
}),
});
module.exports = upload;
and my routes:
// routes.js
let upload = require('../controllers/uploadController')
const singleUpload = upload.single("image");
// post list product page
router.post('/list-product', singleUpload, listController.list__post)
Upvotes: 0
Views: 617
Reputation: 26
I'm not a pro on this but i can think in one solution:
I see you handle the request first in the upload, so there you can save on the request the value of the Key, and not use directly the Date.now() on the name of the image when you create the file
So you should do: req.imageName = new Date.now().toString() And in the name change that creation of the name with req.imageName
Then in the next controller handling the request, you have access to the name on the object "req" provided to the function.
NOTE: new Date.now() IS NOT a good unique key if you have concurrent request for different clients, you have a high probability of getting the same number if you have too much requests at the same time.
NOTE 2: I can think on uuid for better unique keys, i don't know too much about others librarys that can solve that problem.
Upvotes: 1