sql >> Database teknologi >  >> NoSQL >> MongoDB

NodeJS tilbagekald efter flere async-funktioner i for-loop

Der er flere tilgange, du kan bruge her baseret på din bekvemmelighed

Brug af async afventer

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)

Brug af $lookup aggregering 3.6

Da mongodb har sin egen kraftfulde $lookup aggregeringsoperatør for at deltage i flere samlinger og sandsynligvis den bedre tilgang uden nogen 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" }
  }}
])

Brug af $lookup aggregering 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" }
  }}
])


  1. spring data mongodb id felt mapping

  2. MongoDB geo afstand/radius til nyttige enheder

  3. Future of Hadoop – Løn og jobforudsigelser i Big Data-analyse

  4. MongoDB - Hvordan definerer man flere datatyper for et felt i Mongoose?