Search code examples
reactjsimagecrudmultermern

How to update image in MERN which is uploaded using Multer?


These are my all Routes :

//Create a Post
router.post("/", upload.single("profile"), createPost);

//Read a Post
router.get("/", readPost);

//Delete a Post
router.delete("/:id", deletePost);

//Update a Post
router.put("/:id",upload.single("profile") updatePost);

This my code for multer setup :

// Multer Image Upload

    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, "uploads");
      },
      filename: function (req, file, cb) {
        cb(null, Date.now() + "_" + file.originalname);
      },
    });
    const upload = multer({ storage: storage });

This is my UpdatePost function for updating post , after updating the post the desc("description") gets updated but the profile(image form name) value gets updated with null. :

//Update a Post
const updatePost = async (req, res) => {
  const { desc } = req.body;
  const profile = req.file ? req.file.filename : null;
  try {
    const updatedPost = await Post.findByIdAndUpdate(
      { _id: req.params.id },
      {
        desc: desc,
        profile: profile,
      }
    );
    res.status(200).json({ updatedPost, sucess: "Post Updated Sucessfully" });
  } catch (error) {
    res.status(404).json({ error: error.message });
  }
};

Solution

  • First of all get the data from database of which you wanna update the image .

    Replace already existing path of image in that data with the path of new image you sent through react and update the data in database using .save() method