1

I'm trying to get a particular user's posts. It's returning me an empty array of posts. Here's my code. I think I have referenced everything correctly, there must be some mistake.

User model

const Schema = mongoose.Schema

const userSchema = new Schema({
    username: { type: String, required: true },
    email: { type: String, reuired: true },
    password: { type: String, required: true },
    posts:[{ type: Schema.Types.ObjectId, ref: "Post" }]
}, { timestamps: true })

Post model

const Schema = mongoose.Schema;

const postSchema = new Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  user: { type: Schema.Types.ObjectId, ref: "User" },
}, { timestamps: true }

router.get("/posts/:id", usersController.getUserPosts)

    getUserPosts: (req, res) => {
        User.findById(req.params.id, async (err, user) => {
            if (err) {
                return res.status(500).json({ error: "Server error" })
            } else if (!user) {
                return res.status(400).json({ error: "No user" })
            } else if (user) {
                user = await User.populate("user", {
                  path: "posts",
                  model: "Post"
              })
            return res.status(200).json({ user })
         }
      })
    }

Edit

The users in the database are:

/users/list

{
    "users": [
        {
            "posts": [],
            "_id": "5e66496fcaf5d6697ca3fdbc",
            "username": "JimmyPage",
            "email": "[email protected]",
            "password": "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
            "createdAt": "2020-03-09T13:49:35.834Z",
            "updatedAt": "2020-03-09T13:49:35.834Z",
            "__v": 0
        },
        {
            "posts": [],
            "_id": "5e66499fcaf5d6697ca3fdbe",
            "username": "AxlRose",
            "email": "[email protected]",
            "password": "$2b$10$H3X3efz02RonlvNXaRPr2eEbflSiFK1ITFdbyT2igUGDK9gDpIJqO",
            "createdAt": "2020-03-09T13:50:23.702Z",
            "updatedAt": "2020-03-09T13:50:23.702Z",
            "__v": 0
        }
    ]
}

The posts look like this:

/posts/list

{
    "posts": [
        {
            "_id": "5e66498ccaf5d6697ca3fdbd",
            "title": "Jimmy Page's post",
            "description": "This is Jimmy Page's post",
            "user": {
                "posts": [],
                "_id": "5e66496fcaf5d6697ca3fdbc",
                "username": "JimmyPage",
                "email": "[email protected]",
                "password": "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
                "createdAt": "2020-03-09T13:49:35.834Z",
                "updatedAt": "2020-03-09T13:49:35.834Z",
                "__v": 0
            },
            "createdAt": "2020-03-09T13:50:04.840Z",
            "updatedAt": "2020-03-09T13:50:04.840Z",
            "__v": 0
        },
        {
            "_id": "5e6649b5caf5d6697ca3fdbf",
            "title": "Axl Rose's Post",
            "description": "This is Axl Rose's Post",
            "user": {
                "posts": [],
                "_id": "5e66499fcaf5d6697ca3fdbe",
                "username": "AxlRose",
                "email": "[email protected]",
                "password": "$2b$10$H3X3efz02RonlvNXaRPr2eEbflSiFK1ITFdbyT2igUGDK9gDpIJqO",
                "createdAt": "2020-03-09T13:50:23.702Z",
                "updatedAt": "2020-03-09T13:50:23.702Z",
                "__v": 0
            },
            "createdAt": "2020-03-09T13:50:45.751Z",
            "updatedAt": "2020-03-09T13:50:45.751Z",
            "__v": 0
        },
        {
            "_id": "5e664b7bf120ab6c0d9999c9",
            "title": "Jimmy Page's second post",
            "description": "This is Jimmy Page's second post\n\n",
            "user": {
                "posts": [],
                "_id": "5e66496fcaf5d6697ca3fdbc",
                "username": "JimmyPage",
                "email": "[email protected]",
                "password": "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
                "createdAt": "2020-03-09T13:49:35.834Z",
                "updatedAt": "2020-03-09T13:49:35.834Z",
                "__v": 0
            },
            "createdAt": "2020-03-09T13:58:19.261Z",
            "updatedAt": "2020-03-09T13:58:19.261Z",
            "__v": 0
        }
    ]
}

I've added the above code in my question. I've been stuck in this like forever like I'm trying to show user's posts in his profile and also planning to show the global feed of all user's posts showing.

It will be great if you could help me out. I will really appreciate it. THANKS.

List posts controller is like this:

listposts:  (req, res) => {
    Post.find({}, async (error, posts) => {
        if (error) {
            return res.status(500).json({ error: "something went wrong" })
        } else if (!posts) {
            return res.status(400).json({ msg: "sorry no posts" })
        } else if (posts) {
            posts = await Post.populate(posts, {
              path: 'user',
              model: 'User'
            });
            return res.status(200).json({ posts })
        }
    })
}

The users document:

{
     "_id" : ObjectId("5e66496fcaf5d6697ca3fdbc"),
      "posts" : [ ],
      "username" : "JimmyPage",
      "email" : "[email protected]",
      "password" : "$2b$10$mu0IcHADj5YVIT/66EEfPOxL3cvEjqDsnJUcrST8ZcatTOcQ42kn6",
      "createdAt" : ISODate("2020-03-09T13:49:35.834Z"),
      "updatedAt" : ISODate("2020-03-09T13:49:35.834Z"), "__v" : 0 
}

{ 
    "_id" : ObjectId("5e66499fcaf5d6697ca3fdbe"),
     "posts" : [ ],
     "username" : "AxlRose",
     "email" : "[email protected]",
     "password" : "$2b$10$H3X3efz02RonlvNXaRPr2eEbflSiFK1ITFdbyT2igUGDK9gDpIJqO",
     "createdAt" : ISODate("2020-03-09T13:50:23.702Z"),
     "updatedAt" : ISODate("2020-03-09T13:50:23.702Z"),
     "__v" : 0 
}

And the posts document:

{ 
    "_id" : ObjectId("5e66498ccaf5d6697ca3fdbd"),
    "title" : "Jimmy Page's post",
    "description" : "This is Jimmy Page's post",
    "user" : ObjectId("5e66496fcaf5d6697ca3fdbc"),
    "createdAt" : ISODate("2020-03-09T13:50:04.840Z"),
    "updatedAt" : ISODate("2020-03-09T13:50:04.840Z"),
    "__v" : 0 
}


{
     "_id" : ObjectId("5e6649b5caf5d6697ca3fdbf"),
     "title" : "Axl Rose's Post",
     "description" : "This is Axl Rose's Post",
     "user" : ObjectId("5e66499fcaf5d6697ca3fdbe"),
     "createdAt" : ISODate("2020-03-09T13:50:45.751Z"),
     "updatedAt" : ISODate("2020-03-09T13:50:45.751Z"),
     "__v" : 0 }


{
     "_id" : ObjectId("5e664b7bf120ab6c0d9999c9"),
     "title" : "Jimmy Page's second post",
     "description" : "This is Jimmy Page's second post\n\n",
     "user" : ObjectId("5e66496fcaf5d6697ca3fdbc"),
     "createdAt" : ISODate("2020-03-09T13:58:19.261Z"),
     "updatedAt" : ISODate("2020-03-09T13:58:19.261Z"), 
     "__v" : 0 
}

1 Answer 1

2

You can use the following method to get the user info and his/her posts.

getUserPosts: async (req, res) => {
  try {
    const user = await User.findById(req.params.id).populate("posts");

    if (!user) {
      return res.status(400).json({ error: "No user" });
    }

    return res.status(200).json({ user });
  } catch (err) {
    return res.status(500).json({ error: "Server error" });
  }
};
Sign up to request clarification or add additional context in comments.

13 Comments

still empty posts im getting..do i have to add post id somewhere. i read in some of the other answers but i couldn't figure out how to get the post id here.
@ubuntu7788 how do you create model for posts collection? It must be something like this mongoose.model("Posts", postSchema ). The Posts here must match Posts here ref: "Posts"
my mongoose model is export const Post = mongoose.model("Post", postSchema, "posts"). I don't know why that third parameter "posts" is needed. It's optional, right?
@ubuntu7788 you need to change your ref like this posts:[{ type: Schema.Types.ObjectId, ref: "Post" }] in the user schema. We are not interested that 3rd parameter.
@ubuntu7788 you are welcome, can you please mark this as answer and upvote?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.