How can I get all post records on my MERN app?

Viewed 28

I am working on a MERN App and this is a basic project in which we allow users to login and create posts from their account and user can follow other users and on the homepage they can see their posts along with posts from their friends as well.

Below I have shared the code to get all posts on the homepage. I have created an admin panel in which I want to get all posts from the database (MongoDB Atlas). I have allowed the admin to delete any post but right now admin has to visit every profile to delete posts I want to show all posts on a single page to make it easy for the admin to delete any post.

Following is the code to get posts for my homepage

//get timeline posts

router.get("/timeline/:userId", async (req, res) => {
  try {
    const currentUser = await User.findById(req.params.userId);
    const userPosts = await Post.find({ userId: currentUser._id });
    const friendPosts = await Promise.all(
      currentUser.followings.map((friendId) => {
        return Post.find({ userId: friendId });
      })
    );
    res.status(200).json(userPosts.concat(...friendPosts));
  } catch (err) {
    res.status(500).json(err);
  }
});
1 Answers

I didn't understant clearly your problem. But if you need to get all your posts here a solution:

const posts = await Post.find().lean(); // you will get an array of posts

Related