1

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

Penny Liu
18k5 gold badges89 silver badges109 bronze badges
asked Aug 30, 2022 at 0:58

2 Answers 2

3

You could use a forEach on req.files:

req.files.forEach(f => product.photos.push(f.location))
answered Aug 30, 2022 at 1:02
Sign up to request clarification or add additional context in comments.

Comments

3

Array.prototype.push() accepts a variable number of arguments. You can spread an array as arguments

product.photos.push(...req.files.map(({ location }) => location));

I'd be inclined to set the photos array within your Product constructor instead

class Product {
 constructor(photos = []) {
 this.photos = photos;
 }
}
const product = new Product(req.files.map(({ location }) => location));
answered Aug 30, 2022 at 1:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.