gpt4 book ai didi

node.js - for循环中多个异步函数之后的NodeJS回调

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:56 27 4
gpt4 key购买 nike

我从 mongodb 获取一个文档,其中包含一个带有该文档注释的数组。评论中是撰写评论的用户的 _id。

我现在需要根据用户的 _id 获取用户名,但遇到了几个问题。

我有以下代码,显然,它不起作用,但我希望它能让您了解我想要完成的任务。

//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)

我查阅了多个文档,但未能找到可行的解决方案。我尝试使用 Promise.all,尝试了很多 async、await,尝试在 for 循环中添加一个计数器并在循环完成后解析 Promise,但到目前为止没有任何效果。

这就是文章在我的数据库中的样子

{
"_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")
}
]
}

我对nodejs和mongodb也很陌生,所以我希望你能帮助像我这样的新手。

感谢您的帮助

最佳答案

您可以根据自己的方便使用多种方法

使用异步等待

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)

使用$lookup聚合3.6

既然mongodb有自己强大的$lookup聚合运算符加入多个集合,可能是无需任何迭代的更好方法

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" }
}}
])

使用$lookup聚合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" }
}}
])

关于node.js - for循环中多个异步函数之后的NodeJS回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53866016/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com