0
router.patch ('/:id', upload.single ('profilePic'), async (req, res) => {
  try {
    // const prevUser = await User.findById (req.params.id).lean ().exec ();

    // const prevPath = prevUser.profile_pic;

    //delete prevfile using prevPath.
    const del = await User.findById ({_id: req.params.id}, function (
      err,
      data
    ) {
      console.log (data);
      if (err) throw err;
      fs.unlink (data.profile_pic);
    });
    console.log (del);
    
    const newUser = await User.findByIdAndUpdate ({
      _id: req.params.id,
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      profile_pic: req.file.path,
    });

    return res.status (201).send ({newUser});
  } catch (e) {
    return res.status (500).send ({message: e.message, status: 'Failed'});
  }
});

  1. I want to update this file and add a different profile pic, i am not getting how to update it as is a form-data, while updating new profile i want to unlink previous one.
nkil
  • 29
  • 3
  • Questions which may help include: https://stackoverflow.com/questions/38882130/node-js-server-side-script-to-update-json-file, https://stackoverflow.com/questions/65378123/how-to-update-only-one-key-in-a-json-file-with-node-js, https://stackoverflow.com/questions/26962420/how-to-update-json-in-the-server-using-express-js, and https://stackoverflow.com/questions/40167278/how-to-live-update-a-json-response-express-nodejs – evolutionxbox Dec 01 '21 at 15:52
  • 1) Load file to string, 2) Parse JSON string to object, 3) Change `profile_url` property of object, 4) Stringify object to JSON string, 5) Write string to file. – CherryDT Dec 01 '21 at 15:52
  • 1. actually i was asking through "patch" api end point. – nkil Dec 01 '21 at 15:59

0 Answers0