'How can I delete a user from my mongoose and node web app?
I have so far got an app where users can register and sign in. I have also implicated a role based system, However I am struggling when it comes to deleting a user. I have looked all over the web but nothing seems to work. I think my delete route is fine, but when I click the delete button nothing happens. I have identified the user id in the url but it doesn't delete. Any help would be much appreciated.
in routes/admin.js
//Delete a user
router.delete('/delete/:id', (req, res, next) => {
try {
User.findByIdAndDelete({_id: req.params.id});
// res.redirect('/admin');
} catch (error) {
res.redirect('/index');
}
});
in views/manage-users.ejs
<form action="/admin/delete/:<%= user.id %>" method="delete">
<button type="submit">DELETE</button>
</form>
Solution 1:[1]
You can do like this.
router.delete("/delete/:id", (req: Request, res: Response) => {
const id = req.params.id;
Links.deleteOne({ _id: id })
.then((data) =>
res.json({
data: data,
})
)
.catch((error) => {
return res.send(error);
});
});
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 |
