skip to Main Content

When I click to delete a post, my console is saying TypeError: post.user.posts.deleteOne is not a function. It giving me this error after deleting.

const post = await Post.findByIdAndDelete(id).populate('user'); This code I am deleting the post from Post Schema

await post.user.posts.deleteOne(post)This code is to delete the post from the User Schema. I populated user and assigned it to post and then delete the user’s post from this code, but I’m getting the error here.

Below is the controller code

export const deletePost = async (req, res) => {
    const { id } = req.params;


    try {
        const post = await Post.findByIdAndDelete(id).populate('user');
        await post.user.posts.deleteOne(post)

        if (!post) {
            return res.status(500).json({ message: "Unable To Delete" })
        }
        res.status(200).json({ message: "Deleted Successfully" })
    } catch (error) {
        console.log(error);
    }
}

Client side delete request

const handleDeleteTrue = async () => {
        try {
            const { data } = await api.delete(`/post/${id}`)
            console.log(data)
            window.location.reload();
        } catch (error) {
            console.log(error.response.data.message);
        }
    };

User model schema

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true,
        unqie: true
    },
    password: {
        type: String,
        required: true,
        minlength: 6
    },
    posts: [{ type: mongoose.Types.ObjectId, ref: "Post", required: true }]
});

export default mongoose.model('User', userSchema);

Im able to delete the post from the post model schema, but in this pic, which shows the user model schema, that same post that was deleted is not deleted here. This is the problem Im trying to solve.
enter image description here

3

Answers


  1. Chosen as BEST ANSWER

    I found out the answer. My user model schema for post was an array so I had to use $pull to delete it. This is the code that worked for me

            await post.user.posts.pull(post)
            await post.user.save()
    

  2. What I can seem to understand in your function below is that you’re trying to delete a single post and also checking if post exists first

    export const deletePost = async (req, res) => {
        const { id } = req.params;
    
    
        try {
            const post = await Post.findByIdAndDelete(id).populate('user');
            await post.user.posts.deleteOne(post)
    
            if (!post) {
                return res.status(500).json({ message: "Unable To Delete" })
            }
            res.status(200).json({ message: "Deleted Successfully" })
         catch (error) {
            console.log(error);
        }
    }
    

    I’d suggest you try this

    
    export const deletePost = async (req, res) => {
        const { id } = req.params;
        try {         
            //check if document exists in mongoDB collection
             if (!mongoose.Types.ObjectId.isValid(id)) {
            return res.status(500).json({ message: "Unable To Delete" })    }
    
            await Post.deleteOne(id)
    
            res.status(200).json({ message: "Deleted Successfully" })
         catch (error) {
            console.log(error);
        }
    }
    
    Login or Signup to reply.
  3. You can’t use findOneAndDelete on populate to delete one object from an array. it doesn’t work that way. Use This Instead.

    const result = await User.findOneAndUpdate(
          { _id: Id },
          { $pull: { post:PostId } },
          { new: true }
        );
    

    You can find More on Pull and Push Operations on BlogLink

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search