NodeJS 在JavaScript中将多个对象推入数组

rqcrx0a6  于 5个月前  发布在  Node.js
关注(0)|答案(2)|浏览(63)

如何将多个对象推入数组

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);
  }
});

字符串
这将推送第一个和第二个对象,假设我有10个文件,我如何编写一行代码来同时推送10个对象?

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


我怎么能让它像一行代码得到整个数组和推到我的数据库

oxcyiej7

oxcyiej71#

您可以在req.files上使用forEach

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

字符串

hrirmatl

hrirmatl2#

Array.prototype.push()接受可变数量的参数。您可以spread数组作为参数

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

字符串
我倾向于在Product构造函数中设置photos数组

class Product {
  constructor(photos = []) {
    this.photos = photos;
  }
}

const product = new Product(req.files.map(({ location }) => location));

相关问题