[英]How to list subcollections in a Cloud Firestore document
假設我將這個最小的數據庫存儲在 Cloud Firestore 中。 如何檢索subCollection1
和subCollection2
的名稱?
rootCollection {
aDocument: {
someField: { value: 1 },
anotherField: { value: 2 }
subCollection1: ...,
subCollection2: ...,
}
}
我希望能夠從aDocument
中讀取 id,但是當我get()
文檔時只顯示字段。
rootRef.doc('aDocument').get()
.then(doc =>
// only logs [ "someField", "anotherField" ], no collections
console.log( Object.keys(doc.data()) )
)
在 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);
});
客戶端 SDK(Web、iOS、Android)目前不支持此功能。
似乎他們在 Node.js 中添加了一個名為getCollections()
的方法:
firestore.doc(`/myCollection/myDocument`).getCollections().then(collections => {
for (let collection of collections) {
console.log(`Found collection with id: ${collection.id}`);
}
});
此示例打印出位於/myCollection/myDocument
的文檔的所有子集合
文檔中沒有詳細說明嗎?
/** * Delete a collection, in batches of batchSize. Note that this does * not recursively delete subcollections of documents in the collection */ function deleteCollection(db, collectionRef, batchSize) { var query = collectionRef.orderBy('__name__').limit(batchSize); return new Promise(function(resolve, reject) { deleteQueryBatch(db, query, batchSize, resolve, reject); }); } function deleteQueryBatch(db, query, batchSize, resolve, reject) { query.get() .then((snapshot) => { // When there are no documents left, we are done if (snapshot.size == 0) { return 0; } // Delete documents in a batch var batch = db.batch(); snapshot.docs.forEach(function(doc) { batch.delete(doc.ref); }); return batch.commit().then(function() { return snapshot.size; }); }).then(function(numDeleted) { if (numDeleted <= batchSize) { resolve(); return; } // Recurse on the next process tick, to avoid // exploding the stack. process.nextTick(function() { deleteQueryBatch(db, query, batchSize, resolve, reject); }); }) .catch(reject); }
這個答案在文檔中
遺憾的是,文檔並不清楚您導入的內容。
根據文檔,我的代碼最終看起來像這樣:
import admin, { firestore } from 'firebase-admin'
let collections: string[] = null
const adminRef: firestore.DocumentReference<any> = admin.firestore().doc(path)
const collectionRefs: firestore.CollectionReference[] = await adminRef.listCollections()
collections = collectionRefs.map((collectionRef: firestore.CollectionReference) => collectionRef.id)
這當然是 Node.js 服務器端代碼。 根據文檔,這不能在客戶端上完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.