7
votes

When I get several documents from a collection, the result is only an array with each doc data.

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

How can I get the name of each doc?

The ideal result would look like this:

{"docname1": {…}, "docname2": {…}, "docname3": {…}}
3
you need to use snapshotChanges()Makah

3 Answers

10
votes
// Print each document 
db.collection("categories")
    .onSnapshot((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(doc.data()); // For data inside doc
            console.log(doc.id); // For doc name
        }
    }
7
votes

When you need to access additional metadata like the key of your Document, you can use the snapshotChanges() streaming method.

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 };
      });

You can review the documentation for further explanation and example

1
votes

This is dart code:

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
        );
      },
    ),