adrianhajdin / project_mern_memories

This is a code repository for the corresponding video tutorial. Using React, Node.js, Express & MongoDB you'll learn how to build a Full Stack MERN Application - from start to finish. The App is called "Memories" and it is a simple social media app that allows users to post interesting events that happened in their lives.
https://youtube.com/playlist?list=PL6QREj8te1P7VSwhrMf3D3Xt4V6_SRkhu
4.95k stars 1.83k forks source link

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

Open AAdewunmi opened 6 months ago

AAdewunmi commented 6 months ago
  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." });
    }
  2. Cause: As of Mongoose version 8 there is no more .findByIdAndRemove() in its place you will have to use .findByIdAndDelete() [Model.findByIdAndDelete()](https://mongoosejs.com/docs/api/model.html#Model.findByIdAndDelete())

  3. 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." });
    }
Goldfish7718 commented 5 months ago

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