Er zijn verschillende benaderingen die u hier kunt gebruiken op basis van uw gemak
Async wait gebruiken
let article = await Article.findOne({ _id: articleid }).lean().exec()
await Promise.all(
article.comment.map(async(obj) => {
const user = await User.findOne({ _id: obj.user })
obj.username = user.username
})
)
console.log(article)
Met behulp van $lookup
aggregatie 3.6
Aangezien mongodb zijn eigen krachtige $lookup
aggregatie-operator om deel te nemen aan meerdere verzamelingen en waarschijnlijk de betere aanpak zonder enige iteratie
Article.aggregate([
{ "$match": { "_id": mongoose.Types.ObjectId(articleid) }},
{ "$unwind": "$comment" },
{ "$lookup": {
"from": "users",
"let": { "userId": "$comment.user" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$$userId", "$_id"] }}}
],
"as": "comment.user"
}},
{ "$unwind": "$comment.user" },
{ "$group": {
"_id": "$_id",
"comment": { "$push": "$comment" },
"completed": { "$first": "$completed" },
"completedAt": { "$first": "$completedAt" }
}}
])
Met behulp van $lookup
aggregatie 3.4
Article.aggregate([
{ "$match": { "_id": mongoose.Types.ObjectId(articleid) }},
{ "$unwind": "$comment" },
{ "$lookup": {
"from": "users",
"localField": "comment.user",
"foreignField": "_id",
"as": "comment.user"
}}
{ "$unwind": "$comment.user" },
{ "$group": {
"_id": "$_id",
"comment": { "$push": "$comment" },
"completed": { "$first": "$completed" },
"completedAt": { "$first": "$completedAt" }
}}
])