0

How can I convert userIDs to usernames of these users when sending data from db? I think it's possible using middlewares, but I don't know how to do it. There is my route

router.get('/recentQuizzes', async (req, res) => {
    const { skip, limit } = req.query
    if (skip >= 0 && limit >= 0) {
        const quizzes = await Quiz.find({})
            .sort({ date: -1 })
            .skip(parseInt(skip))
            .limit(parseInt(limit))
        res.json(quizzes)
    }
})

and the author is saves as ObjecdId userID in DB, creating quiz requires user to be verified by jwt, but these quizzes can be created by other users. I need to convert authorID to author name while sending to user. I also tried something like this

router.get('/recentQuizzes', async (req, res) => {
    const { skip, limit } = req.query
    if (skip >= 0 && limit >= 0) {
        const quizzes = await Quiz.find({})
            .sort({ views: -1 })
            .skip(parseInt(skip))
            .limit(parseInt(limit))
        quizzes.forEach(async item => {
            const { username } = await User.findById(item.author)
            console.log(username)
            item.author = username
        })
        res.json(quizzes)
    }
})

but my forEach function doesn't overwrite author to its username, but console.logs correct username

1 Answers1

1

Try using map function instead of forEach to modify quizzes and get a new modified array.

let modifiedQuizzes = await Promise.all(quizzes.map(async (item)=>{
      const { username } = await User.findById(item.author)
      console.log(username)
      item.author = username
      return item;
})

);

gladprog
  • 126
  • 2
  • 9
  • okay it almost works, but when i call console.log(item) inside quizzes.map it's as it should be, but when I console.log(modifiedQuizzes) outside that map function, it is [ Promise { } ] – Dawid Szemborowski Apr 28 '21 at 11:42
  • edited. reference https://stackoverflow.com/questions/40140149/use-async-await-with-array-map – gladprog Apr 28 '21 at 12:02