How to export dynamic nested collection data in cloud firestore using node js?

Viewed 620

enter image description hereenter image description hereenter image description hereHow to export dynamic nested collection in cloud firestore using node js?

var express = require("express");
var router = express.Router();
var admin = require("firebase-admin");
var databaseURL = "databaseURL"; // Initiate databaseURL
var serviceAccount = require("../serviceaccount.json"); // Initiate serviceAccount
if (admin.apps.length) {
  admin.app();
} else {
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: databaseURL
  })
}
var firestoredb = admin.firestore();
var CollectionName = request.body.CollectionName;
var SubCollectionName = request.body.SubCollectionName;
router.get("/", async (req, res, next) => {
  await firestoredb.collection(CollectionName).doc().collection(SubCollectionName).doc().get()
    .then(async snapshot => {
      var snap_size = snapshot.size;
      console.log("snap_size", snap_size)
      var arr_Collection_Details = [];
      snapshot.forEach(async doc => {
        var CollectionData = doc.data();
        arr_Collection_Details.push(CollectionData)
        fs.writeFile("filename.json", JSON.stringify(arr_Collection_Details), function (err) {
          if (err) {
            console.log("error:", err.message);
            res.json({
              returncode: 201,
              message: err.message
            })
          } else {
            console.log("Data Exported Sucessfully");
            res.json({
              returncode: 200,
              message: "Data Exported Sucessfully"
            })
          }
        });
      });
    })
  .catch((err) => {
    res.json({
      returncode: 201,
      message: err.message
    })
  })
});
module.exports = router;

I take subcollection data but i need nested collection data that nested collection name are dynamically.

how to write the query for nestedcollection

1 Answers

You ask in the comments:

Is it possible to fetch all sub collections and its documents of a collection without knowing its internal sub collection names or document ids?

While it is not possible, with the mobile and web client SDKs, to retrieve the list of subcollections of a document, it is possible with the Cloud Firestore server client libraries, and in particular with Firebase Admin Node.js SDK. This is explained in detail in the following article (Disclaimer, I'm the author)

Since you use the Admin SDK, you can use this technique, as follows:

//Get the path of the parent pocument
const docPath = "col1/doc2/subcol4/doc7";  //For example

const collections = await admin.firestore().doc(docPath).listCollections();

const promises = [];

collections.forEach(collRef => {
    promises.push(collRef.get());
})
const querySnapshotsArray = await Promise.all(promises);

querySnapshotsArray.forEach(querySnapshot => {
   querySnapshot.forEach(doc => {
       console.log(doc.id, " => ", doc.data());
   });
 });

Note that there is a similar listCollections() method to list all the root collections of your Firestore database.

Related