TSR
TSR

Reputation: 20627

get a list of document from firestore

I have a collection accounts structured as follow:

enter image description here

Now I have a user who owns two accounts:

enter image description here

How do I make a query to fetch the account of this user and return it as a resolution of a promise?

Here is what I tried. It returns []

 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)
            });

        })
    }

Upvotes: 1

Views: 118

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

You don't need to use a transaction, since you are just reading some documents. Since you want to execute, in parallel, two (or more) asynchronous methods which return a promise (i.e. the two get() for the accounts docs) you should use Promise.all().

Something along the following lines should work:

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 => {
        ....
    });
 }

Note that I have used the "classic" definition for the DocumentReferences (i.e. db.collection('users').doc(user_id) and db.collection('accounts').doc(id)) since I am not 100% sure what are this.ref and this.db in your case. Just adapt as you wish!

You may also rework it with return new Promise((res, rej) => {}) as you wish but the overall philosophy remains the same.

Upvotes: 1

Related Questions