saving multiple files in mongodb using multer

Viewed 663

i am creating an p2p ecommerce platform and i need assistance in saving images, i basically have two problems at the moment. 1.) my first problem is saving the images... so lets say i have a mongoose model for a product as follows:

title: {
    type: String,
    required: true
  },
  subtitle: {
    type: String
  },
  productImage: [
    {
      imageUrl: {
        type: String,
        required: true
      }
    }
  ],
  details: {
    modelNumber: {
      type: String
    }

now i want to save multiple images to a product so i can use a carousel later on, so i am running into the problem where i dont know how to do this, i have currently written this code to save the images

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const dir = './uploads';

    // create uploads
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
    }

    cb(null, dir);
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname + '-' + Date.now());
  }
});

let upload = multer({
  storage,
  limits: {
    fileSize: 1024 * 1024 * 10
  },
  fileFilter
}).array('productImage', 4);

router.post("/products", auth, uploads,  async(req, res) =>{

try{

const product = new Product({

title: req.body.title,
subtitle: req.body.subtitle,
productImage: [{imageUrl: req.file.path}],
blah blah
})

}catch{
blah blah
}

})

basically i think i am going about it the wrong way in saving multiple files for a product, so i want to know how better can this be done or if i should re structure my model or any other solutions

2.) i have a problem because i am using express validator to check my fields when i send my request in form data i get errors on the fields even though the fields are populated with the right data, ... is there anyway i can correct this?

Thank you...any help would be seriously needed

0 Answers
Related