skip to Main Content

I just want to ask

I tried deleting data from mongo atlas using this code

//DELETE POST
router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    if (post.username === req.body.username) {
      try {
        await post.delete();
        res.status(200).json("Post has been deleted...");
      } catch (err) {
        res.status(500).json(err);
      }
    } else {
      res.status(401).json("You can delete only your post!");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

But when I test it using Postman, it doesn’t do anything and gives 500 internal server error.
Postman to test the code

Even though the data is in the mongo atlas, like this picture
The data is inside

I just want to know where I went wrong when writing this code, because I just started to create a project. Thank you for your attention!

router.delete("/:id", async (req, res) => {
  if (req.body.userId === req.params.id) {
    if (req.body.password) {
      const salt = await bcrypt.genSalt(10);
      req.body.password = await bcrypt.hash(req.body.password, salt);
    }
    try {
      await Post.delete();
      res.status(200).json("Post has been deleted...");
    } catch (err) {
      res.status(500).json(err);
    }
  } else {
    res.status(401).json("You can delete only your account!");
  }
});

2

Answers


  1. @seyn kindly show the function , error might be in that function

    Login or Signup to reply.
  2. //DELETE POST
    router.delete("/:id", async (req, res) => {
      try {
        const post = await Post.findById(req.params.id);
        if (post.username === req.body.username) {
          try {
            post = await Post.findByIdAndDelete(req.params.id);
            res.status(200).json("Post has been deleted...");
          } catch (err) {
            res.status(500).json(err);
          }
        } else {
          res.status(401).json("You can delete only your post!");
        }
      } catch (err) {
        res.status(500).json(err);
      }
    });

    This will work iguess, you can also use filter function.

    router.delete("/:id", async (req, res) => {
      try {
        const post = await Post.findById(req.params.id);
        if (post.username === req.body.username) {
          const posts = await Post.find();
          const filteredPosts = posts.filter(post => post.id !== req.params.id);
          res.status(200).json(filteredPosts);
        } else {
          res.status(401).json("You can delete only your post!");
        }
      } catch (err) {
        res.status(500).json(err);
      }
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search