【发布时间】:2018-04-09 22:00:05
【问题描述】:
我会自动执行 Firestore 数据库的备份过程。
这个想法是遍历根文档以构建 JSON 树,但我没有找到一种方法来获取可用于文档的所有集合。我想这可能是因为在 Firestore 控制台中我们可以看到树。
有什么想法吗?
【问题讨论】:
标签: firebase google-cloud-firestore
我会自动执行 Firestore 数据库的备份过程。
这个想法是遍历根文档以构建 JSON 树,但我没有找到一种方法来获取可用于文档的所有集合。我想这可能是因为在 Firestore 控制台中我们可以看到树。
有什么想法吗?
【问题讨论】:
标签: firebase google-cloud-firestore
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 );
});
});
【讨论】:
它可以在网络上(客户端 js)
db.collection('FirstCollection/' + id + '/DocSubCollectionName').get().then((subCollectionSnapshot) => {
subCollectionSnapshot.forEach((subDoc) => {
console.log(subDoc.data());
});
});
感谢@marcogramy 评论
【讨论】:
更新
API 已更新,现在函数为 .listCollections()
https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#listCollections
getCollections() 方法可用于 NodeJS。
示例代码:
db.collection("Collection").doc("Document").getCollections().then((querySnapshot) => {
querySnapshot.forEach((collection) => {
console.log("collection: " + collection.id);
});
});
【讨论】:
.listCollections(), googleapis.dev/nodejs/firestore/latest/… 。感谢stackoverflow.com/a/57248728/2162226。这让我朝着正确的方向前进,谢谢
如果您使用的是 Node.js 服务器 SDK,您可以在 DocumentReference 上使用 getCollections() 方法:
https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/DocumentReference#getCollections
此方法将返回一个CollectionReference 对象数组的承诺,您可以使用这些对象访问集合中的文档。
【讨论】:
正如其他人提到的,在服务器端你可以使用getCollections().来获取所有的根级集合,在db上使用它,如下所示:
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}`);
});
});
【讨论】:
listCollections()