rgoncalv
rgoncalv

Reputation: 6035

Firebase Cloud Firestore - How to query two sub-collections simultaneously?

I want to query two sub-collections of a DocumentReference.

I tried doing the following:

var promise1 = admin.firestore().collection(`players/${id}/collection1`).get();
var promise2 = admin.firestore().collection(`players/${id}/collection2`).get();

return Promise.all(promise1, promise2)

The problem though, is that by doing the following I get the following error:

TypeError: (var)[Symbol.iterator] is not a function at Function.all (native) at exports.onSubmission.functions.firestore.document.onCreate (/user_code/index.js:671:20)

So, I tried nesting them as below and it worked fine.

 return admin.firestore().collection(`players/${id}/collection1`).get().then(foundersSnapshot => {
    return admin.firestore().collection(`players/${id}/collection2`).get().then(metricsSnapshot => {

However, when deploying I get the warning saying

Avoid nesting promises

So, what are the best practices in this case? I would prefer doing through Promise.all but it doesn't work. Also, it would output two collections as results in the then(results => { So, in this case, could I safely regard results[0] as "collection1" and `results[1] as "collection2"?

Upvotes: 1

Views: 289

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

Promise.all() requires a single array parameter. Note the square brackets around promise1 and promise2 that make an inline array out of them:

Promise.all([promise1, promise2])

Upvotes: 1

Related Questions