提问者:小点点

Firestore-在一个循环中进行深度收集查询


我有一个firestore对象,如下所示:

{
  countries:[
    country1: {
      cities: [
        city1: {date_added: timestamp},
        ...
      ]
    }
    ...
  ]
}

所以我希望在一个查询中获得一个城市列表。 我知道我可以像(我在firestore函数中)

const cities = [];

admin.firestore().collection('countries/')
    .get()
    .then(countriesSnapshot => {
      countriesSnapshot .forEach( countryDoc => {
        admin.firestore().collection('countries/' + countryDoc.id + '/cities/')
          .get()
          .then(citySnapshot => {
            citySnapshot.forEach( cityDoc => {
              cities.push(cityDoc.id);
            });
          }).catch();
      });
    }).catch();

但这会造成双重影响,我只想在所有问题都解决后再处理。 我可以用承诺。all,但我想知道是否有更简单的方法--比如

admin.firestore().collection('countries/{countryId}/cities').get().then(citySnapshot ...

共1个答案

匿名用户

如果要跨所有城市集合查询,可以使用集合组查询:

let cities = db.collectionGroup('cities');
cities.get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
    console.log(doc.id, ' => ', doc.data());
  });
});

这将返回所有国家的所有城市。