Horkos
Horkos

Reputation: 381

JS - Mongoose DEL query issue

I'm stumbling on this DELETE query for a specific POST. It's on a MERN stack, so count Mongoose and Express in this snippet from app.js :

app.delete('/api/post/delete/:id', (req, res) => {
  try {
    Post.findOneAndDelete({ _id: req.params.id });
    res.status(200).send({ message: "Post deleted successfully" });
    console.log(`Post ${req.params.id} deleted`);
  } catch (error) {
    res.status(500).send(error);
  }
});

The _id is definitely passing, for my console sends me logs with the exact post _id, but still, it won't be deleted in MongoDB. Thank you for helping,

Upvotes: 2

Views: 183

Answers (2)

iamphduc
iamphduc

Reputation: 333

Your line res.status(200).send({ message: "Post deleted successfully" }); and console.log(`Post ${req.params.id} deleted`); should be wrap like this.

Post.findOneAndDelete({ _id: req.params.id }, function (err, docs) {
    if (err) {
        console.log(err);
    } else {
        res.status(200).send({ message: "Post deleted successfully" });
        console.log(`Post ${req.params.id} deleted`);
    }
});

Upvotes: 1

Horkos
Horkos

Reputation: 381

Found the thing : needed to make it an async function in order to the Post.delete to take effect.

 app.delete('/api/post/delete/:id', async(req, res) => {
  try {
    await Post.findOneAndDelete({ _id: req.params.id });
    res.status(200).send({ message: "Post deleted successfully" });
    console.log(`Post ${req.params.id} deleted`);
  } catch (error) {
    res.status(500).send(error);
  }
});

Upvotes: 0

Related Questions