How to update file/images with patch api and multer package

Viewed 382

As you can see my codes, I created a user model and importing here(inside controller) and also imported a upload middleware from my another directory folder where codes is written for uploading file/images using multer package and everything is ok and perfectly upload the file using post api.

what i am doing here -> created a user schema model, and a middleware for uploading file using multer package and controller for crud operation post,get ,patch and delete, post api is ok its working fine but for patch

what i want to do -> I want to update profile_pic through (req.params.id) when i use patch api in postman to update so its uploaded in upload directory but at the same time i got an error called(Cast to ObjectId failed for value) in the postman and seems not not updated my data

const express = require('express');
const User = require('../models/user.model');
const upload = require('../middlewares/file_upload')
const router = express.Router();


router.post('/',upload.single("profilePic"),async (req, res) => {
    try {
        const users = await User.create({
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            profile_pic:req.file.path,
        })
        return res.status(201).send({users})

    } catch(e) {
        return res.status(500).json({message:e.message,status:"Failed"})
    }
})



`Here below the problem is, Can anyone help me out to this problem`

router.patch('/:id',upload,async (req, res) => {


    try {
       
        const user = await User.findByIdAndUpdate({
            first_name:req.params.id,
            last_name:req.params.id,
            profile_pic:req.file.path,
          
        },{req.body}, { new:true})

        return res.status(201).send({user})

    } catch(e) {
        return res.status(500).json({message:e.message,status:"Failed"})
    }
})

module.exports = router;
1 Answers

Try this code:

router.patch('/:id',upload.single("profilePic"),async (req, res) => {

try {
   
    const user = await User.findByIdAndUpdate(
       mongoose.Types.ObjectId(req.params.id),
       { profile_pic: req.file.path }
    );
    return res.status(201).send({user})

} catch(e) {
    return res.status(500).json({message:e.message,status:"Failed"})
}

})

The problem is, that you are finding the user by first_name and last_name, which are no ids. You need to find the user by the object id.

Related