Building an express route for uploading images to a listing. The route controller uploads the images to an S3 bucket and responds with a data object. Within the data object is Location and this is what I want to push to an array. I can console.log(data.Location) and it works every time, why can't I push to the array of imageUrls?? No matter what I try pushing to the array(even a string I type) nothing happens.
Here is the route controller:
exports.imageUpload = async function (req, res) {
//checks for files,
//also checks that listingId is right length to not throw a CastId error in mongoose
//idk if that is completely right to do
if (!req.files || !req.params.listingId)
return res
.status(400)
.json({ success: false, msg: 'No files given OR no listing ID given' }); //TODO change this for production
const listing = await Listing.find({ _id: req.params.listingId }).limit(1); //returns array with listing being first index
if (!listing || listing.length < 1)
return res
.status(400)
.json({ success: false, msg: 'Listing does not exist' });
//config for s3 bucket
const s3 = new AWS.S3({
accessKeyId: process.env.awsaccessKey,
secretAccessKey: process.env.awssecretKey,
Bucket: bucketname,
});
s3.createBucket(function () {
const files = req.files;
var imageUrls = [];
files.map((file) => {
var params = {
Bucket: 'kret-static/listingImages',
Key: file.originalname,
Body: file.buffer,
ACL: 'public-read',
};
s3.upload(params, function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data.Location); //this works just fine no matter how many images
imageUrls.push(data.Location); //why will this not do anything???????
}
});
});
console.log(imageUrls); //always results in an empty array even though the data.Location is there
});
// //listing model method for pushing the images into DB instance
// listing.pushImages(req.files);
// try {
// await listing[0].save();
// return res.json({ success: true });
// } catch (err) {
// return res.json({ error: err });
// }
};