Search code examples
node.jsfirebasegoogle-cloud-firestoreasync-awaitfirebase-admin

Firebase Firestore not returning documents


I was attempting to fetch all documents from a collection in a Node.js environment. The documentation advises the following:

import * as admin from "firebase-admin";
const db = admin.firestore();
const citiesRef = db.collection('cities');
const snapshot = await citiesRef.get();
console.log(snapshot.size);
snapshot.forEach(doc => {
  console.log(doc.id, '=>', doc.data());
});

I have 20 documents in the 'cities' collection. However, the logging statement for the snapshot size comes back as 0.

Why is that?

Edit: I can write to the Firestore without issue. I can also get details of a single document, for example:

const city = citiesRef.doc("city-name").get();
console.log(city.id);

will log city-name to the console.


Solution

  • Ensure that Firebase has been initialized and verify the collection name matches your database exactly, hidden spaces and letter case can break the link to Firestore. One way to test this is to create a new document within the collection to validate the path.

    db.collection('cities').doc("TEST").set({test:"value"}).catch(err => console.log(err));
    

    This should result in a document in the correct path, and you can also catch it to see if there are any issues with Security Rules.

    Update

    To list all documents in a collection, you can do this with the admin sdk through a server environment such as the Cloud Functions using the listDocuments() method but this does not reduce the number of Reads.

    const documentReferences = await admin.firestore()
            .collection('someCollection')
            .listDocuments()
    const documentIds = documentReferences.map(it => it.id)
    

    To reduce reads, you will want to aggregate the data in the parent document or in a dedicated collection, this would double the writes for any updates but crush read count to a minimal amount.