Comment API

To implement the add comment API, we will set up a PUT route as follows to update the post.

mern-social/server/routes/post.routes.js:

router.route('/api/posts/comment')    .put(authCtrl.requireSignin, postCtrl.comment)

The comment controller method will find the relevant post to be updated by its ID, and push the comment object received in the request body to the comments array of the post.

mern-social/server/controllers/post.controller.js:

const comment = (req, res) => {  let comment = req.body.comment  comment.postedBy = req.body.userId  Post.findByIdAndUpdate(req.body.postId, {$push: {comments: comment}}, {new: true})  .populate('comments.postedBy', '_id name')  .populate('postedBy', '_id name')  .exec((err, result) => { if (err) { ...

Get Full-Stack React Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.