【问题标题】:get a list of document from firestore从 Firestore 获取文档列表
【发布时间】:2018-09-08 00:41:22
【问题描述】:

我有一个集合accounts,结构如下:

现在我有一个拥有两个帐户的用户:

如何进行查询以获取此用户的帐户并将其作为承诺的解决方案返回?

这是我尝试过的。它返回[]

 getAccounts(user_id, userRef) {
        return new Promise((res, rej) => {
            this.db.runTransaction((transaction) => {
                return transaction.get(userRef.doc(user_id)).then((userDoc) => {
                    let accounts = []
                    if (!userDoc.exists) {
                        throw "User Document does not exist!";
                    }
                    let userData = userDoc.data()
                    let accountList = userData.accounts

                    for (var id in accountList){
                        transaction.get(this.ref.doc(id)).then(ans => {
                            accounts.push(ans.data())
                        }).catch(e => {
                            console.log(e)

                        })
                    }
                    return accounts
                }).then(function (ans) {
                    res(ans)
                }).catch((e) => {
                    console.log(e)
                });
            }).catch(function (err) {
                console.error(err);
                rej(err)
            });

        })
    }

【问题讨论】:

    标签: node.js firebase nosql google-cloud-firestore


    【解决方案1】:

    您不需要使用事务,因为您只是阅读一些文档。由于您想要并行执行两个(或更多)返回承诺的异步方法(即帐户文档的两个 get()),您应该使用 Promise.all()

    以下几行应该可行:

    getAccounts(user_id, userRef) {
       return db.collection('users').doc(user_id).get()  //replaced since I am not sure what is this.db in your case
       .then(userDoc => {
           const promises = []
           if (!userDoc.exists) {
               throw "User Document does not exist!";
           }
           let userData = userDoc.data()
           let accountList = userData.accounts
    
           for (var id in accountList){
               promises.push(db.collection('accounts').doc(id).get())
           })
           return Promise.all(promises)
       })
       .then((results) => {
           return results.map(doc => doc.data());
        })
        .catch(err => {
            ....
        });
     }
    

    请注意,我对DocumentReferences(即db.collection('users').doc(user_id)db.collection('accounts').doc(id))使用了“经典”定义,因为我不能100% 确定在您的情况下this.refthis.db 是什么。随心所欲地适应!

    您也可以根据需要使用return new Promise((res, rej) => {}) 对其进行修改,但总体理念保持不变。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 2018-09-03
      • 2022-01-20
      • 1970-01-01
      • 2019-07-04
      • 2022-01-06
      • 2019-06-07
      • 1970-01-01
      相关资源
      最近更新 更多