0
votes

I am making an API from express and mongo. When I perform a get operation for specific documents from a "posts" collection using id, I also perform another get operation from "comments" collection using same postId to obtain all related comment to the post. Before I return it I pushed all obtain comments from "comment" collection to an array inside document from post collection then return it. Problem is in postman when I return that post, it shows an empty array.

Edit: it only shows those comments if I return selectedPost.comments in both postman and console not if I return selectedPost?


  try {
        let selectedPost = await Post.findOne({_id:id}) 
        let comments = await Comments.find({postId:id})
        selectedPost.comments = [...comments]

        console.log(selectedPost.comments)
        res.json({selectedPost})

    } catch (error) {
        console.error(error)
    }

2

2 Answers

0
votes

MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections.

https://mongoosejs.com/docs/populate.html

0
votes

Make sure you are getting data in selectedPost and comments

try {
  let selectedPost = await Post.findOne({_id:id}) 
  let comments = await Comments.find({postId:id})
  selectedPost.comments = [...comments]

  let response = {...selectedPost, comments }
  console.log(response)
  res.json({response})

} catch (error) {
  console.error(error)
}