Marina
Marina

Reputation: 187

How to delete comment that is inside of Post schema?

I'm working on social network app where user can make post and comment. I'm trying to delete comment that is inside of a post. I work with MERN (mongoose, express, react, nodejs). I can successfully delete post, but don't know how to delete its comment.

This is my Mongo connection:

const db = config.get('mongoURI') mongoose.connect(db,{useNewUrlParser: true,useUnifiedTopology: true})
.then(() => console.log('Connected to MongoDB.'))
.catch(err => console.log('Fail to connect.', err))

this is Post Schema

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const PostSchema = new Schema({
    userID: {
        type: Schema.Types.ObjectId,
        ref: 'user'
    },
    content: {
        type: String,
        required: true
    },
    registration_date: {
        type: Date,
        default: Date.now
    },
    likes: [
        {
            type: Schema.Types.ObjectId,
            ref: "user"
        }
    ],
    comments: [
        {
            text: String,
            userID: {
                type: Schema.Types.ObjectId,
                ref: 'user'
            }
        }
    ]
})

module.exports = User = mongoose.model('posts', PostSchema)

and here is where i tried to delete it:

router.delete("/comment/:postId/:commentId", auth, function (req, res) {
    Post.findByIdAndUpdate(
        (req.params.postId),
        { $pull: { comments: req.params.commentId } },
        { new: true }
    )
    .then(post => console.log(post)
            .then(() => {
                res.json({ success_delete: true })
            })
            .catch(() => res.json({ success_delete: false })))
}); 

Upvotes: 2

Views: 934

Answers (1)

midnightgamer
midnightgamer

Reputation: 454

Well, I think you are creating an app named DevConnector. So I wrote code for the same in the past.

router.delete('/comment/:id/:comment_id', auth, async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);

    // Pull out comment
    const comment = post.comments.find(
      comment => comment.id === req.params.comment_id
    );

    // Make sure comment exists
    if (!comment) {
      return res.status(404).json({ msg: 'Comment does not exist' });
    }

    // Check user
    if (comment.user.toString() !== req.user.id) {
      return res.status(401).json({ msg: 'User not authorized' });
    }

    // Get remove index
    const removeIndex = post.comments
      .map(comment => comment.user.toString())
      .indexOf(req.user.id);

    post.comments.splice(removeIndex, 1);

    await post.save();

    res.json(post.comments);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

Upvotes: 1

Related Questions