PUT
will replace all current data of the target resource with the content in the requestPUT
requests also need to be targeted by /:id
to ensure the correct record is updatedDELETE
PUT
POST
GET
PUT
or PATCH
DELETE
axios
, express
, mongoose
async await
functions within a try catch next
and test that the functions return the expected outputs with Thunderclient/InsomniaPUT
form
to update a bookputBooks
and updates databaseapp.put('books/:id', putBooks)
Function
async function putBooks(req, res, next) {
try {
let id = req.params.id;
let updatedBooksData = req.body;
let updatedBooks = await Books.findByIdAndUpdate(id, updatedBooksData, {new: true, overwrites: true});
res.status(200).send(updatedBooks);
} catch(error) {
next(error);
}
}
updatedBooks = async (bookToUpdate) => {
try {
let url = `${process.env.REACT_APP_SERVER}/books/${bookToUpdate._id}`;
let updatedBookObj = await axios.put(url, bookToUpdate);
let updatedBookArr = this.state.books.map(book => {
return book._id === bookToUpdate._id
? updatedBookObj.data
: book;
});
this.setState({
books: updatedBookArr
});
} catch(error) {
console.log('Error: ', error.response.data);
}
}