'Delete item from mongoDB from client side
I've created a React app where you can post vinyls you have in your collection. Now I've implemented a button that is able to remove the selected item from the DOM but I also want the specific item to beremoved from the database. I'm using node with mongoose and that's (for now) my delete route:
vinylsRouter.delete('/:id', (req, res) => {
const id = req.params.id
Vinyl.findByIdAndDelete(id)
.then((deletedVinyl) => {
console.log(deletedVinyl)
})
.catch((error) => {
res.status(500).send(error);
})
});
I also tried to store the id of the specific vinyl _id into a variable and then delete it. So I also created a get route to try to get the _id of the vinyl.
vinylsRouter.get('/:id', authenticateJWT, (req, res) => {
const id = req.params.id;
Vinyl.findById(id, { __v: 0, updatedAt: 0, createdAt: 0 })
.then((user) => {
res.send(user)
})
.catch((error) => {
res.status(500).send(error)
})
});
But now I don't know how to code in the client side to make that when an user clicks in the delete button, it sends something to get the id of the vinyl and then delete it.
Solution 1:[1]
First put some response when the delete works:
vinylsRouter.delete('/:id', (req, res) => {
const id = req.params.id
Vinyl.findByIdAndDelete(id)
.then((deletedVinyl) => {
res.status(200).send(deletedVinyl);
})
.catch((error) => {
res.status(500).send(error);
})
});
If are you trying to do a API You can use express/nodejs, and do res.status(200).json({message: "my message"})
.
Second you can use a library like axios:
axios.delete(`http://localhost:xyz/vynils/`, { id })
.then(res => {
console.log(res);
console.log(res.data);
})
https://www.digitalocean.com/community/tutorials/react-axios-react
And send for the server when the users click in the delete button.
You can use postman to test your delete endpoint before you use this on client-side (frontend), remember select delete in the dropbox and put a auth token (JWT) in the Authorization tab, or you can remove, only for test the auth middleware:
Say me if is this what you want to do.
Solution 2:[2]
app.delete('/product/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await productCollection.deleteOne(query);
res.send(result);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sunjatun Ahmed Runa |