繁体   English   中英

如何使用angular firestore获取集合中的文档列表

[英]how to get list of document in a collection, using angular firestore

我正在尝试获取集合中的文档列表,但我没有获取任何文档,这是我正在尝试的代码 - `

    schoolProductCollectionFetch(schoolName){
    
       const school = this.db.collection(schoolName)
       this.school$ = school.snapshotChanges().pipe(map(schoollist=>schoollist.map(s=>{
         const data = s.payload.doc.id;
         console.log(data);
         return data;
       })));
       return this.school$
     
      }

数据库格式:SchoolCollection->Documents->ProductCollection

SchoolCollection:{
   1st:{products:{}},
   2nd:{products:{}},
}

已尝试在 firestore 中表示数据格式,我想获得第一个、第二个,它们是 SchoolCollection、Schema Snap 的文档 ID:

架构截图 注意:如果需要更多详细信息来理解查询,请告诉我

不确定您是否仍然需要这个,但您可能想尝试collectionGroup('Name of collection')

代码应类似于以下内容:

    this.afs.collectionGroup('Users')
      .valueChanges().subscribe(users => {
      
      //this.userNames is an "Any" before my constructor.
      this.userNames = users

      //for loop allows me to get all the document's data
      for (let i = 0; i < users.length; i++) {
        
        //these const allow me to play with If conditionals
        const userEmail = this.userNames[i].email;
        const userRole = this.userNames[i].role;

        if (userRole == "User") {
          continue;
        } else {
          console.log(userEmail);
        }
      }
    });

HTH 在任何...

你可以尝试这样的事情:

schoolProductCollectionFetch(): Observable<School[]> {
  return this.db
    .collection('schoolName')
    .snapshotChanges()
    .pipe(
      map((snaps) =>
        snaps.map((snap) => {
          return new School({
            id: snap.payload.doc.id,
            ...(snap.payload.doc.data() as {}),
          });
        }),
      ),
      first(),
    );
}

获取数据并创建它的实例后,您可以重构此代码,使其更具可读性。 希望这可以帮助!

我的第一个问题是:您将参数“schoolName”传递给函数,然后执行this.db.collection(schoolName) 现在,学校名称实际上是集合的名称,还是集合中文档的 ID?

尝试此操作时,您在控制台输出中遇到什么错误? 您是否设置了 Firestore 权限以允许请求?

您发布的数据库模式令人困惑,也许您从 firebase 控制台设置的实际屏幕截图可能更有用。

编辑

要使用 firestore 获取集合的数据,您必须构建指向所需集合的正确路径。 在您的示例中,执行类似this.db.collection(schoolName).get()的操作将获取该集合中的所有文档。 注意:这不会得到任何子集合! 在撰写本文时,Firebase 不支持这种类型的查询。

假设您想要获取子集合“kitProducts”的所有文档。 这可以通过执行this.db.collection(schoolName + "/1st/kitProducts").get()来实现。 这将返回位于 schoolName 集合中 ID 为“1st”的文档下的子集合“kitProducts”中的所有文档。 您必须建立这些路径才能查询它们。

你似乎在收集实时听众的领域。 如果这是您的意图,您应该使用onSnapshot()函数。 以前面的示例为例,编写类似this.db.collection(schoolName + "/1st/kitProducts").onSnapshot()的内容。 在这种情况下,只要编辑、删除或添加 kitProducts 子集合中的文档,就会触发一个事件。

更多阅读:

https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection

https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM