Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get documents names in Firestore

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": {…}}
like image 943
José Camelo de Freitas Avatar asked Dec 23 '17 14:12

José Camelo de Freitas


People also ask

How do I get all the collection names in firestore?

You can do the following: const admin = require("firebase-admin"); const db = admin. firestore(); db. listCollections() .

How do I find the number of documents in a collection firestore?

If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.


2 Answers

// 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
        }
    }
like image 50
Piyushh Avatar answered Sep 28 '22 03:09

Piyushh


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

like image 21
Benoit Avatar answered Sep 28 '22 03:09

Benoit