首页 > 解决方案 > 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"?

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


Promise.all()需要一个数组参数。注意周围的方括号promise1promise2它们构成了一个内联数组:

Promise.all([promise1, promise2])

推荐阅读