如何列出Cloud Firestore文档中的子集合

sky*_*ize 9 javascript firebase google-cloud-firestore

假设我将此最小数据库存储在Cloud Firestore中.我怎么能检索的名字subCollection1subCollection2

rootCollection {
    aDocument: {
        someField: { value: 1 },
        anotherField: { value: 2 }
        subCollection1: ...,
        subCollection2: ...,
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够只读取ID aDocument,但只有字段出现在我get()的文档中.

rootRef.doc('aDocument').get()
  .then(doc =>

    // only logs [ "someField", "anotherField" ], no collections
    console.log( Object.keys(doc.data()) )
  )
Run Code Online (Sandbox Code Playgroud)

Dan*_*ath 5

在 Node.js 中,您将使用“ListCollectionIds”方法

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

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

// Iterate over all elements.
var formattedParent = client.anyPathPath("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]");

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

客户端 SDK(Web、iOS、Android)当前不支持此功能。


小智 5

似乎他们添加了一个调用getCollections()Node.js的方法:

firestore.doc(`/myCollection/myDocument`).getCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found collection with id: ${collection.id}`);
  }
});
Run Code Online (Sandbox Code Playgroud)

此示例打印出文档的所有子集合 /myCollection/myDocument