简体   繁体   中英

FIRESTORE - How to fetch values of a collection inside a document?

In my Firestore Database, I have a collection APP .

It has a document doc1 .

doc1 further has a child collection coll1 .

Consider the following example.

let db = firebaseApp.firestore();

db.collection('APP').doc('doc1').get()
  .then(doc => {
    let doc1Data = doc.data();
  });

How can I possibly check for a collection in the response. Or when I already know that there is a child collection coll1 , how can I loop through its documents.

If you don't know the collection ids you can use the listCollectionIds method to get them all:

var firestore = require('firestore.v1beta1');

var client = firestore.v1beta1({
  // optional auth parameters.
});

var formattedParent = client.anyPathPath("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]");

client.listCollectionIds({parent: formattedParent}).then(function(responses){
    var collectionIds = responses[0];
    for (var i = 0; i < collectionIds.length; ++i) {
        // doThingsWith(collectionIds[i])
    }
})
.catch(function(err) {
    console.error(err);
});

But, it sounds like you already know it's called col1 , so it's easier - just reference it:

db.collection('APP').doc('doc1').collection('col1').get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            console.log(doc.id, '=>', doc.data());
        });
    })
    .catch(err => {
        console.log('Error getting documents', err);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM