这应该可以使用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);
})
编辑:虽然上面的代码可以运行if the SDK allowed it,但由于额外的/,它目前会抛出一个关于有奇数段的错误。
目前,只要您的所有城市 ID 的长度相同(就像使用默认的 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" 的城市也在城市集合中,那么它的结果也会包含在内。