i would to automate backup process of a firestore database. The idea is to loop over root document to build a JSON tree. but i didn\'t find a way to get all collections ava
Its possible on web (client side js)
db.collection('FirstCollection/' + id + '/DocSubCollectionName').get().then((subCollectionSnapshot) => {
subCollectionSnapshot.forEach((subDoc) => {
console.log(subDoc.data());
});
});
Thanks to @marcogramy comment
firebase.initializeApp(config);
const db = firebase.firestore();
db.settings({timestampsInSnapshots: true});
const collection = db.collection('user_dat');
collection.get().then(snapshot => {
snapshot.forEach(doc => {
console.log( doc.data().name );
console.log( doc.data().mail );
});
});
Update
API has been updated, now function is .listCollections()
https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#listCollections
getCollections() method is available for NodeJS.
Sample code:
db.collection("Collection").doc("Document").getCollections().then((querySnapshot) => {
querySnapshot.forEach((collection) => {
console.log("collection: " + collection.id);
});
});
If you are using the Node.js server SDK you can use the getCollections()
method on DocumentReference
:
https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/DocumentReference#getCollections
This method will return a promise for an array of CollectionReference
objects which you can use to access the documents within the collections.
As mentioned by others, on the server side you can use getCollections().
To get all the root-level collections, use it on the db like so:
const serviceAccount = require('service-accout.json');
const databaseURL = 'https://your-firebase-url-here';
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: databaseURL
});
const db = admin.firestore();
db.settings({ timestampsInSnapshots: true });
db.getCollections().then((snap) => {
snap.forEach((collection) => {
console.log(`paths for colletions: ${collection._referencePath.segments}`);
});
});