Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore can't get empty docs

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?

like image 532
mkelle Avatar asked Jul 01 '18 08:07

mkelle


Video Answer


1 Answers

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.

like image 171
perepm Avatar answered Oct 01 '22 17:10

perepm