0

im trying get the user model of comment author on a post (three interacting models here) and im trying to just send it back in the initial fetch when retrieving the writing - i can retrieve the comment and the ID of the user who made the comment, but i want the user object so that i can display username and a link to the profile of the user who posted the comment. currently my controller function looks like:

async function showWriting(req, res) {
  const writing = await Writing.findById(req.params.id);
  const writingUser = await User.findById(writing.user);
  const comments = await Comment.find({writing: writing._id})
  let commentAndUser=[]
  await comments.forEach((comment) =>{
    commentAndUser.push({comment: comment.comment, user: comment.populate('user').execPopulate()})
  })
  console.log(commentAndUser)
  return res.json({ writing: writing, comments: commentAndUser, writingUser: writingUser });
}

i have tried to findByID(comment.user) but that just sends a query object because i cannot do an await at a lower level function (like the forEach with the comment and user) im wondering if there is a work around? currently with this iteration the comment user returns as a pending promise that i cannot figure out how to resolve. any ideas would be great!

p.s. my code is a bit jumbled here from trying several things... dont judge!

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
deitz88
  • 33
  • 5
  • 1
    I'm not sure what you mean by "resolve promise before return", but since the `showWriting` function is declared `async` it implicitly returns a Promise, so any consuming logic needs to handle calling `showWriting` asynchronously, i.e. awaiting it or using a Promise chain. – Drew Reese Aug 08 '21 at 02:05
  • 1
    If you are trying to await the forEach loop see https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Arye Eidelman Aug 08 '21 at 02:09
  • y'all were super helpful, and that link to the other stack overflow problem fixed it, thank you so much!! – deitz88 Aug 08 '21 at 02:34

0 Answers0