NodeJS callback after multiple async-functions in for-loop

后端 未结 2 517
谎友^
谎友^ 2021-01-24 10:47

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 ge

2条回答
  •  故里飘歌
    2021-01-24 11:45

    There are serveral approaches you can use here based on your convenience

    Using async await

    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)
    

    Using $lookup aggregation 3.6

    Since mongodb has its own powerfull $lookup aggregation operator to join multiple collection and probably the better approach without any iteration

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

    Using $lookup aggregation 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" }
      }}
    ])
    

提交回复
热议问题