Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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);
Posted
Updated 11-Aug-20 23:06pm
v2
Comments
Richard MacCutchan 11-Aug-20 7:09am    
I cannot see the line of code that refers to req.files[0].location. But all you need is something like:
for (int i = 0; i < number_of_files; ++i)
{
    copy(req.files[i].location, destination[i]) // or whatever required code
}

1 solution

// We loop throw the req.files array and store their locations in the temporal files array
    for (let i = 0; i < req.files.length; i++) {
        let file = req.files[i].location
        files.push(file)
      }

          let newProduct = new ProductModel({
                              imagePath: files
                                   })
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900