April 2020
Intermediate to advanced
716 pages
18h 55m
English
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, which is defined in the following code, will find the relevant post to be updated by its ID and push the comment object that's received in the request body to the comments array of the post.
mern-social/server/controllers/post.controller.js:
const comment = async (req, res) => { let comment = req.body.comment comment.postedBy = req.body.userId try { let result = await Post.findByIdAndUpdate(req.body.postId, {$push: {comments: comment}}, {new: true}) .populate('comments.postedBy', ...Read now
Unlock full access