【发布时间】:2018-04-25 14:49:39
【问题描述】:
我在 Firebase 的 Cloud Firestore 数据库中有一个集合,其中包含如下子集合:
myCollection
doc1
statistics
doc1
doc2
doc3
doc2
statistics
doc1
doc2
doc3
statistics
doc1
doc2
doc3
doc4
doc4
statistics
等等。
例如,根据查询,我可能会从集合中提取 doc1、doc2 和 doc4。现在,对于其中的每一个,我需要查询它们各自的子集合以获取相关统计信息。
到目前为止,我在 AngularJS 应用中的解决方案是:
/**
* Gets aggregate views for queried docs.
* @param {![firebase.firestore.DocumentSnapshot]} docs - the queried documents
*/
$scope.getTotalViews = (docs) => {
let promises = [];
docs.forEach(doc => {
promises.push($scope.getTotalDocumentViews(doc.id));
});
$q.all(promises).then(totalViewsArray => {
// TODO: Sum the array to get aggregate views for queried documents
// Only outputs some of the time
console.log(totalViewsArray);
});
};
/**
* Gets all view statistics from a given document's subcollection.
*/
$scope.getTotalDocumentViews = (id) => {
let deferred = $q.defer();
firebase.firestore().collection("myCollection").doc(id).collection("statistics").where("type", "==", "view").get().then(snapshot => {
deferred.resolve(snapshot.size);
});
return deferred.promise;
};
我遇到的问题是,由于 myCollection 上的查询可能返回许多文档,因此遍历所有这些文档并查询它们的子集合似乎效率极低。不仅如此,虽然上面的代码在某些时候确实会成功,但很多时候它会抛出错误:
Uncaught (in promise) Error: transaction closed
我还尝试在事务中执行多个子集合查询,但效果不佳,因为我不只检索一个文档,而是从子集合中查询可能数百个文档。
如何有效地查询一组多个文档的子集合?
【问题讨论】:
标签: angularjs firebase google-cloud-firestore