Home > Software design >  Put Not Working to Update with Axios Mongoose
Put Not Working to Update with Axios Mongoose

Time:08-05

I am trying to set up an edit feature to edit a post. Right now I am trying to update a specific post by ID and then I'll make it dynamic.

I can get axios to send the PUT request but I don't receive any indication that it is received on the router. Also the ID I have set it showing up correctly in the URL.

I'm not sure how to send the data over to the router so it can find the ID.

Edit component

function handleSubmit(event){
        event.preventDefault()
        axios ( {
            url: `/api/${props.data[0]._id}`,
            method: 'PUT',
           headers: { "Content-Type": "multipart/form-data" },
            id: props.data[0]._id
        })
        .then(() => {
            console.log(`data has been sent to the server from axios: ${props.data[0]._id}`)
        })
        .catch(() => {
            console.log('Data could not be sent from axios')
        })

    } 

Router

 router.put('/:id', async (req, res) => {
      try {
    
        const updatedGratitude = await PostGratitude.findByIdAndUpdate(req.params.id)
    
        res.status(200).json(updatedGratitude)
    
      } catch (err){
    
        next(err)
    
    }
    })

CodePudding user response:

This is because you forgot the update body on method. Try this:

PostGratitude.findByIdAndUpdate(req.params.id, req.body)

instead of :

await PostGratitude.findByIdAndUpdate(req.params.id)

Because mongoose can not know what to update :D

CodePudding user response:

if you are editing a post then you should send the data in the request as well like a title: "" and description: "" or something and in the in the router, you could write something like this :

function handleSubmit(event) {
event.preventDefault()
axios({
    url: `/api/${props.data[0]._id}`,
    method: 'PUT',
    headers: { "Content-Type": "application/json" },
    data: {
        title: '',
        description: ''
    }
})
    .then((response) => {
        console.log(response)
    })
    .catch((err) => {
        console.log(err)
    })

}

you need to pass the arguments as to what to update as well, here is an example of a code that I wrote

router.put('/updatentry/:id',fetchuser, async (req, res) => {
var success = false
try {
    const { title, description } = req.body
    let newentry = { title: title , description: description
     }
    

    let old_entry = await Journal.findById(req.params.id);
    if (!old_entry) {
        return res.status(404).send({ success, error: 'Not Found'})
    }
    
    const update_entry = await Journal.findByIdAndUpdate(req.params.id, { $set: newentry }, { new: true })
    return res.send(res: update_entry)
} catch (error) {
    return res.status(500).send(error: 'Internal Server Error')
}

})
  • Related