project_mern_memories icon indicating copy to clipboard operation
project_mern_memories copied to clipboard

Part 2: TypeError: PostMessage.findByIdAndRemove is not a function

Open AAdewunmi opened this issue 1 year ago • 1 comments

  1. Encountered the following error when I clicked the delete button.

TypeError: PostMessage.findByIdAndRemove is not a function

  1. Source:
server/controllers/post.js - deletePost()
export const deletePost = async (req, res) => {
    const { id } = req.params;
    if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No post with id: ${id}`);
    await PostMessage.findByIdAndRemove(id); **<== Error Source ===>** 
    res.json({ message: "Post deleted successfully." });
}
  1. Cause: As of Mongoose version 8 there is no more .findByIdAndRemove() in its place you will have to use .findByIdAndDelete() Model.findByIdAndDelete()

  2. Fix: use findByIdAndDelete()

export const deletePost = async (req, res) => {
  const { id } = req.params;
  if (!mongoose.Types.ObjectId.isValid(id))
    return res.status(404).send(`No post with id: ${id}`);
  await PostMessage.findByIdAndDelete(id); **<== Fix ===>** 
  res.json({ message: "Post deleted successfully." });
}

AAdewunmi avatar Jan 07 '24 15:01 AAdewunmi

I've create a pull request #184 addressing this change 😄

Goldfish7718 avatar Jan 13 '24 05:01 Goldfish7718