Firestore - Get document collections

后端 未结 5 1965
谎友^
谎友^ 2020-12-28 21:32

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

相关标签:
5条回答
  • 2020-12-28 21:52

    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

    0 讨论(0)
  • 2020-12-28 22:00
    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 );
    
      });
    
    });
    
    0 讨论(0)
  • 2020-12-28 22:02

    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);
            });
        });
    
    0 讨论(0)
  • 2020-12-28 22:13

    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.

    0 讨论(0)
  • 2020-12-28 22:14

    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}`);
        });
    });
    
    0 讨论(0)
提交回复
热议问题