I get a document from a mongodb which contains an array with comments for that document. In the comment is the _id of the user which wrote the comment.
I now need to get the username based on the _id of the user, but I'm running into several problems.
I have the following code which, obviously, doesn't work, but I hope it can give you an idea of what I'm trying to accomplish.
//MORE CODE... (No need to show this here, just a promise, some try catch and so on)
let article = await Article.findOne({_id:articleid})
for(var i = 0; i<=article.comment.length-1; i++){
User.findOne({_id:article.comment[i].user}).then((user)=>{
article.comment[i].username = user.username
})
}
return resolve(article)
I looked up several documentations but wasn't able to find a working solution. I tried using Promise.all, played around with a lot of async, await, tried to add a counter into the for-loop and resolve the promise after the loop finished but nothing worked so far.
This is what the article looks like in my db
{
"_id" : ObjectId("5c18c1cbc47e5e29d42e4b0e"),
"completed" : false,
"completedAt" : null,
"comment" : [
{
"_id" : ObjectId("5c18c95e328c8319ac07d817"),
"comment" : "This is a comment",
"rating" : [ ],
"user" : ObjectId("5c18b76e73236d2168eda2b4")
},
{
"_id" : ObjectId("5c18fb578de5741f20a4e2bd"),
"comment" : "Another comment",
"rating" : [ ],
"user" : ObjectId("5c18b76e73236d2168eda2b4")
}
]
}
I'm rather new to nodejs and mongodb aswell so I hope you can help a newbie like me.
Thank you for your Help
awaitin the loop (each findOne) or await aPromise.allover amapinstead of a `loop. That said, the actual correct way to do this in Mongo would be to bulk-update and not find and update the documents one-by-one