push multiple objects into an array in javascript

Issue

how can i push multiple object into an array

router.post(`/products`, upload.array("photos" , 10), async (req, res) => {
  console.log(res);
  try {
    let product = new Product();
    product.photos.push(req.files[0].location);
    product.photos.push(req.files[1].location);
    await product.save();
    console.log(Product);
    res.json({
      status: true,
      message: "save succes",
    });
  } catch (error) {
    console.log(error);
  }
});

this pushes the 1st and 2nd objects, lets say i have 10 files how can i write a line of code to push the 10 objects at once

  product.photos.push(req.files[0].location);
    product.photos.push(req.files[1].location);

how can i make it one line of code like getting the whole array and push to my database

Solution

You could use a forEach on req.files:

req.files.forEach(f => product.photos.push(f.location))

Answered By – Nick

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published