在Firestore中获取文档名称

时间:2017-12-23 14:43:00

标签: firebase angularfire2 google-cloud-firestore

当我从集合中获取多个文档时,结果只是包含每个doc数据的数组。

firestore.collection("categories").valueChanges().subscribe(data => {
    console.log(data);
    // result will be: [{…}, {…}, {…}]
};

如何获取每个文档的名称?

理想的结果如下:

{"docname1": {…}, "docname2": {…}, "docname3": {…}}

3 个答案:

答案 0 :(得分:3)

当您需要访问其他元数据(如文档的密钥)时,您可以使用snapshotChanges()流媒体方法。

firestore.collection("categories").valueChanges().map(document => {
      return document(a => {
        const data = a.payload.doc.data();//Here is your content
        const id = a.payload.doc.id;//Here is the key of your document
        return { id, ...data };
      });

您可以查看documentation以获取进一步说明和示例

答案 1 :(得分:1)

这是飞镖代码:

child: StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
          .collection('your collection')
          .snapshots(), // path to collection of documents that is listened to as a stream
      builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
        return ListView(
          children: snapshot.data.docs.map((DocumentSnapshot doc) { // get document data
            return yourWidget( // return a widget for every document in the collection
               docId: doc.id // get document name
            );
          }).toList(), // casts to list for passing to children parameter
        );
      },
    ),

答案 2 :(得分:0)

// this prints each document individual 
db.collection("categories")
    .onSnapshot((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(doc.data()); // For data inside doc
            console.log(doc.id); // For doc name
    }
}