0

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.

isoaxe
  • 177
  • 2
  • 11

1 Answers1

2

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.

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20
  • Thanks DIGI. I have no issues writing to the Firestore, hence the 20 document already created. – isoaxe Jun 24 '21 at 08:22
  • I should clarify that the document `snapshot` has collections which in turn have a document which finally hold the data. I'm just after the document names at `snapshot` level. – isoaxe Jun 24 '21 at 08:28
  • you must manage that independently in a dedicated document, scraping a collection retrieves the documents data including the document id – DIGI Byte Jun 24 '21 at 09:02
  • Shouldn't I be able to do this without a dedicated document though? Surely this is what the example I linked in the documentation demonstrates. – isoaxe Jun 24 '21 at 10:00
  • I've also updated the question. It's possible for me to get data from a single document, just not for a collection of them. – isoaxe Jun 24 '21 at 10:02