API for posts by a user

To retrieve posts that have been shared by a specific user, we need to add a route endpoint that will receive the request for these posts and respond accordingly to the requesting client- side.

On the backend, we will define another post-related route that will receive a query to return posts by a specific user, as follows.

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

router.route('/api/posts/by/:userId')
.get(authCtrl.requireSignin, postCtrl.listByUser)

The listByUser controller method in post.controller.js will query the Post collection to find posts that have a matching reference in the postedBy field to the user specified in the userId param in the route. The listByUser controller method will look as follows.

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

const listByUser = async (req, res) => {
try {
let posts = await Post.find({postedBy: req.profile._id})
.populate('comments.postedBy', '_id name')
.populate('postedBy', '_id name')
.sort('-created')
.exec()
res.json(posts)
} catch(err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}

This query will return the list of posts that were created by a specific user. We need to call this API from the frontend, which we will do in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset