Search code examples
node.jsmongodbmongoosemulter

Multiple files upload to mongoDB using Multer and Node


how could I upload multiple files to mongoDB using Node and multer. This is my try (of course unsuccessful) to handle it. uploadImg.array() seems to work well since it creates files locally. The problem is that I can not create new uploads in mongoDB

router.post("/img", auth, uploadImg.array("path", 12), async (req, res) => {
  try {
    Promise.all(
      req.files.map(async (file) => {
        const newUpload = new Uploads({
          _id: new Types.ObjectId(),
          path: file.path,
          owner: req.user.userId,
        });

        return await newUpload.save();
      })
    );

    res.status(201).json(newUpload);
  } catch (e) {
    res
      .status(500)
      .json({ message: "Something went wrong in /uploads/img", error: e });
  }
});

req.files look like that:

 [
   {
     fieldname: 'path',
     originalname: 'cover.jpg',
     encoding: '7bit',
     mimetype: 'image/jpeg',
     destination: 'uploads/',
     filename: '1608637632307cover.jpg',
     path: 'uploads\\1608637632307cover.jpg',
     size: 77716
   },
   {
     fieldname: 'path',
     originalname: 'mainImg.jpg',
     encoding: '7bit',
     mimetype: 'image/jpeg',
     destination: 'uploads/',
     filename: '1608637632310mainImg.jpg',
     path: 'uploads\\1608637632310mainImg.jpg',
     size: 111086
   }
 ]

Any ideas? :)


Solution

  • This solution works great, all you need is to handle the res.status:

    router.post("/img", auth, uploadImg.array("path", 12), async (req, res) => {
      Promise.all(
        req.files.map(async (file) => {
          const newUpload = new Uploads({
            _id: new Types.ObjectId(),
            path: file.path,
            owner: req.user.userId,
          });
    
          return await newUpload.save();
        })
      )
        .then(res.status(201).json("files successfully uploaded"))
        .catch((e) => {
          res
            .status(500)
            .json({ message: "Something went wrong in /uploads/img", error: e });
        });
    });