Home > Net >  How to list all non existent documents in a collection?
How to list all non existent documents in a collection?

Time:02-04

Say I have the following structure: collectionA/documentA/collectionB/documentB But I have set documentB directly to the above path (without explicitly creating collectionA, documentA or collectionB), so the document "documentA" is a non existent document that does not show in queries if I list all documents of collectionA even with admin sdk. However the firebase web console somehow manages to list such documents. Not only that, I have also seen a third party app Firefoo list such documents and somehow even paginate the results. How can I achieve this?

CodePudding user response:

Turns out this can be achieved with the Firestore REST API v1 using the listDocuments endpoint and setting query param showMissing to true.

CodePudding user response:

All Firestore queries are based on having some data about that document present in the index that is used for the query. There is no public API to show non-existing documents.

The Firebase console shows these documents based on getting a list of all collections, and then building a data model from that.

CodePudding user response:

In Firebase Firestore, a document is considered to exist if it has been created with at least one field. If you've created a document "documentB" directly within the path collectionA/documentA/collectionB/documentB, then this document will exist in the Firestore database, even if the parent documents "documentA" and "collectionB" do not exist.

To achieve the same behavior as the Firebase web console or Firefoo, you will need to write a custom query to retrieve these "orphaned" documents. One way to do this is to query all documents in the parent collection (collectionA/collectionB) and then filter out the ones that have a specific structure in the document ID, such as "documentA/documentB".

Here's an example in the Firestore admin SDK for Node.js:

const db = firebase.firestore();
const collectionRef = db.collection('collectionA/collectionB');

collectionRef.get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      const docId = doc.id;
      if (docId.startsWith('documentA/')) {
        console.log(doc.data());
      }
    });
  })
  .catch((err) => {
    console.error(err);
  });

This will retrieve all documents in the collection collectionA/collectionB, and then filter out the ones that start with "documentA/" in the document ID, which correspond to the "orphaned" documents. You can then paginate the results as needed.

  • Related