12
votes

I have collection of documents where the id of the doc is the users id. Lets call these user documents.

Each "user document" contains a subcollection of chat messages. But not all "user documents" contains any fields (data, other than the subcollection).

I wan't to return all the doc in the collection that don't have any fields, but have a subcollection, but I seems this is not possible?

var allUserDocs = {}, 
    count = 0,
    users = firestore.collection("users");

users.get().then(snapshot => {
    snapshot.forEach(doc => {           
        count++;
        allUserDocs[count] = doc.data();            
    });

    allUserDocs.count = count;
    res.status(200).send(allUserDocs);          
})

this code only returns the docs that contains fields, not the docs that only have a subcollection? Is there a way to return all?

How can i get a list of all document ids in the collection? both empty and non-empty ones? or how can I add a field to all the docs without fields if i cant access them?

2
I seems like their is a "showMissing" feature in the firestore API made to show all documents with no data. Bu can this flag be set on a nodejs collection query, so that the snapshot will show all empty docs? I need to get the path to all empty docs..mkelle

2 Answers

2
votes

There is a listDocuments method that retrieves all documents, missing or not, that have a subcollection. Here's the page in the docs that explains it.

Something like this might be what you are looking for:

let collectionRef = firestore.collection('col');

return collectionRef.listDocuments().then(documentRefs => {
   return firestore.getAll(...documentRefs);
}).then(documentSnapshots => {
   for (let documentSnapshot of documentSnapshots) {
      if (documentSnapshot.exists) {
        console.log(`Found document with data: ${documentSnapshot.id}`);
      } else {
        console.log(`Found missing document: ${documentSnapshot.id}`);
      }
   }
});

You would not care whether the docRef exists or not.

Nevertheless, it does not sound like a good solution to have empty documents. What is the logic you were pursuing with an architecture where users can be empty, but messages underneath them still matter? Maybe if you still need to access them you can add a boolean variable to determine if the user is active or not, instead of leaving a blank document.

0
votes

Use doc.id

users.get().then(snapshot => {
    snapshot.forEach(doc => {           
        count++;
        allUserDocs[doc.id] = doc.data();            
    });

    allUserDocs.count = count;
    res.status(200).send(allUserDocs);          
})