这是我的数据库结构。
城市->地标->景点(每个景点都是一个集合)
查询
列出某一特定城市的所有景点。
溶液
将city_id保存在每个吸引文档中
使用基于city_id的集合组查询和筛选器获取特定城市的吸引力。
我的问题
与其在每个吸引文档中保存city_id,不如将文档指定给collectionGroupQuery,后者现在只在这个特定文档下的子集合中搜索。
在上面的例子中,我指定了城市文档的完整路径,并且我应该能够列出所有景点,而无需基于city_id进行过滤。
发布于 2021-06-19 18:50:04
这应该可以使用FieldPath.documentId()。
每个文档的数据中都有一个隐藏的__name__字段,这是FieldPath.documentId()的目标。
对于正常的集合查询,FieldPath.documentId()只是文档的ID。但是,对于集合组查询,这个值是文档的路径。
我们应该能够使用它找到以给定城市的文档路径开始的所有匹配文档路径,如下所示:
const cityRef = firebase.firestore().doc('cities/cityId');
firebase.firestore().collectionGroup('attractions')
.orderBy(firebase.firestore.FieldPath.documentId())
.startAt(cityRef.path + "/"),
.endAt(cityRef.path + "/\uf8ff")
.get()
.then((querySnapshot) => {
console.log("Found " + querySnapshot.size + " docs");
querySnapshot.forEach((doc) => console.log("> " + doc.ref.path))
})
.catch((err) => {
console.error("Failed to execute query", err);
})编辑:虽然上面的代码将运行如果SDK允许的话,但由于额外的/,它目前抛出了一个关于有奇数段的错误。
现在,只要您的所有城市if都是相同的长度(如果使用默认的docRef.add(),它们将是相同的),下面的代码将起作用:
const cityRef = firebase.firestore().doc('cities/cityId');
firebase.firestore().collectionGroup('attractions')
.orderBy(firebase.firestore.FieldPath.documentId())
.startAt(cityRef.path),
.endAt(cityRef.path + "\uf8ff")
.get()
.then((querySnapshot) => {
console.log("Found " + querySnapshot.size + " docs");
querySnapshot.forEach((doc) => console.log("> " + doc.ref.path))
})
.catch((err) => {
console.error("Failed to execute query", err);
})如果文档ID有不同的长度,那么上面的块就会失败。假设您只需要"/cities/New York"下的文档,如果另一个名为"New Yorkshire"的城市也在城市集合中,它也会包含它的结果。
https://stackoverflow.com/questions/68049541
复制相似问题