首页 > 解决方案 > 仅将现有子集合放入列表 firebase(flutter)

问题描述

我一直在尝试将子集合的文档快照放在列表中。它的代码是这样的: -

getcoffeebuyerlist() async {
      DocumentSnapshot coffeebuyers;
      List<DocumentSnapshot> finalCoffeBuyerList = [];
      for (var i = 0; i < profiles.length; i++) {
        coffeebuyers = await Firestore.instance
            .collection('profileData')
            .document(profiles[i].uid)
            .collection('coffeeprices')
            .document(profiles[i].uid)
            .get();
        finalCoffeBuyerList.add(coffeebuyers);
      }
      return finalCoffeBuyerList;
    }

有两个配置文件,其中只有一个有子集合'coffeeprices'

我的疑问是通过尝试获取子集合的快照,我是否会自动为不存在子集合的第二个配置文件创建一个空文档并将其放入finalCoffeBuyerList列表中?

或者只有那些(在我的情况下是一个)已经存在的子集合被添加到这个列表中?

标签: firebaseflutterfirebase-realtime-database

解决方案


您在此处的代码将永远不会创建任何文档。 get()如果文档尚不存在,则不会创建文档。您应该检查返回的DocumentSnapshot以查看该文档是否确实存在。像这样的东西:

if (coffeebuyers.exists) {
  finalCoffeBuyerList.add(coffeebuyers);
}

创建文档的唯一方法是使用add()set()


推荐阅读