【问题标题】:Firestore - getting data from a reference like 'collectionName/{id}' and iterating over the resulting listFirestore - 从“collectionName/{id}”之类的引用中获取数据并遍历结果列表
【发布时间】:2020-12-06 14:43:14
【问题描述】:

我正在尝试从“anunturi_postate”参考列表中获取所有数据。 推送到列表的变量“post_data”在循环中看起来没问题,但在循环之外,列表是空的。

我从控制台和 firestore 模拟器添加了一张图片,以便更好地了解我正在尝试做的事情。

// db = firebase.firestore()
async function postedByUser(){

    let query = await db.collection("users").doc($current_user.uid).get()

    let user_posts = []
    // anunturi_postate it's a field name which holds an array
    await query.data().anunturi_postate.forEach(async (doc) => {
        let post = await db.doc(doc.path).get()
        let post_data = await post.data() 
        console.log(post_data) // data looks ok
        user_posts.push(post_data)
    })

    console.log("user_posts:", user_posts) // here it's empty
    return user_posts
}

let user_posts 
postedByUser().then(data => {
    user_posts = data
})

// here it's empty
console.log("After func call: ", user_posts)

【问题讨论】:

    标签: javascript google-cloud-firestore


    【解决方案1】:

    async/await 无法在 forEach 循环中以您期望的方式工作。该循环不会返回您可以等待的承诺,并且在继续执行以下代码之前不会完成。请改用 for 循环。此外,您可以像使用 DocumentReference 对象一样使用每个引用。

        let user_posts = []
        const array = query.data().anunturi_postate
        for (let ref of array) {
            let post = await ref.get()
            let post_data = await post.data() 
            console.log(post_data) // ok
            user_posts.push(post_data)
        })
    
        console.log("user_posts:", user_posts)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2021-12-07
      • 2021-02-24
      • 1970-01-01
      • 2013-09-28
      相关资源
      最近更新 更多