Home > database >  How can I get list of sub collections from doc in firestore using nodejs?
How can I get list of sub collections from doc in firestore using nodejs?

Time:01-08

Helloo, I m really new to firebase technology. Can anyone help me please? I want to get list of sub collections if doc have sub collections.

db.collection("Class 1").get().then((querySnapshot) => {
    const tempDoc = []
    querySnapshot.forEach((doc) => {
       tempDoc.push({ id: doc.id, ...doc.data() }) // some of doc have one or more sub-collections
    })
    console.log(tempDoc)
 })

How can i get names of sub-collection If doc have sub-collection? Here is the result which I want to get.

const tempDoc = [  //The Result Which I want
    {
      id: "One",
      data : "something-1",
      sub_collection : null,
    },
    {
      id: "Two",
      data : "something-2",
      sub_collection : ["sub collection - 1", "sub collection - 2"],
    },
    {
      id: "Three",
      data : "something-3",
      sub_collection : ["sub collection"],
    },
]

CodePudding user response:

As explained in the documentation, with the Admin SDK for Node.js, you can use the listCollections() method which lists all subcollections of a document reference.

const sfRef = db.collection('Class 1').doc('...');
const collections = await sfRef.listCollections();
collections.forEach(collection => {
  console.log('Found subcollection with id:', collection.id);
});

In your case you need to use Promise.all() as follows (untested ):

const docsData = [];

db.collection("Class 1").get()
.then((querySnapshot) => {
    
    const promises = [];
    querySnapshot.forEach((doc) => {
       docsData.push({ id: doc.id, ...doc.data() });
       promises.push(doc.ref.listCollections())
    })
    return Promise.all(promises);
})
.then(subcollsArray => ({   // Arrays of Array of subcollections
    const resultsArray = [];
    subcollArray.forEach((subcollArray, idx) => {
       resultsArray.push({ ...docsData[idx], sub_collections: subcollArray})
    })

    console.log(resultsArray)

});

Note that retrieving a list of collections is not possible with the mobile/web client libraries, but there are workarounds, see this article.

CodePudding user response:

If you're using this function in other part of your project, make it async:

/* Did you try this? */
const fetchDocs = async() => {
  const tempDoc = [];
  await db.collection("Class 1").get()
    .then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        tempDoc.push({
          id: doc.id,
          ...doc.data()
        });

      });
      console.log(tempDoc);
    });
  return tempDoc;
};

fetchDocs()
  .then((data) => {
    if (data.sub_collection) {
      // do something
    }
  })

  • Related