May 2018
Intermediate to advanced
470 pages
13h 54m
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 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) { ...Read now
Unlock full access