I'm trying to upload multiple files from my NodeJs application to a MongoDB database using Multer. But the problem is when I'm saving the location of the file in my database only one file location is saved while others are ignored. This is because in my function I'm only saving the 1st array element by using req.files[0].location. I need a workaround to create a loop and save all the file locations instead of hardcoding position of an array element in the req.files. I need to save the files as
"imagePath": [
{
"small": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1592947173797",
"big": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1592947173797"
},
{
"small": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1592947173799",
"big": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1592947173799"
},
{
"small": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1592947173711",
"big": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1592947173711"
}
Below is my function. I need help with the model and saving multiple imagePath locations in the above manner. Any sort of help is appreciated!
What I have tried:
route.js
const ProductController = require('./../controllers/productController');
const appConfig = require("./../config/appConfig");
const multer = require('multer');
const aws = require('aws-sdk');
const multerS3 = require('multer-s3');
const path = require('path');
const s3 = new aws.S3({ accessKeyId: "***", secretAccessKey: "***" });
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'mean-ecom',
metadata: function (req, file, cb) {
cb(null, {fieldName: file.originalname + path.extname(file.fieldname)});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())}})});
let setRouter = (app) => {
let baseUrl = appConfig.apiVersion;
app.post(baseUrl+'/post-product', upload.any('imagePath'), ProductController.postProduct)}
module.exports = {
setRouter: setRouter}
ProductController.postProduct:
const ProductModel = mongoose.model('Product')
let postProduct = (req, res) => {
let newProduct = new ProductModel({
imagePath: req.file[0].location})
newProduct.save((err, result) => {
if (err) { console.log('Error at saving new Product :: ProductController', err);
res.send(err);
} else {
console.log('Successfully saved new Product'); res.send(result) }
})}
productModel.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let productSchema = new Schema(
{
imagePath: {
type: String,
default: '' }})
mongoose.model('Product', productSchema);