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