想知道如何使用函数过滤 Firestore 文档集合,其中某些函数参数是集合文档的值。
假设有一些 Firestore 表单文档集合
{
pointOfInterest: "Some string label"
longitude: -100.123
latitude: 50.456
}
还有一些代码可以检索用户的地理坐标(在我的例子中,通过react-native),例如
const getCurrentLatLong = () => {
// do some stuff, then...
return { latitude: someNumber, longitude: someOtherNumber }
}
最终想要做的是运行类似的东西
let currentLocation = getCurrentLatLong()
let filteredSet = firebase
.firestore()
.collection('MyCollection')
// filtering each individual document
.filter(function (document, currentLocation) {
let docLat = document.latitude
let docLong = document.longitude
return distance(
{latitude: docLat, longitude: docLong},
currentLocation)
< SOME_CONST_DISTANCE
})
因此,最终会得到集合中与 currentLocation 距离小于 SOME_CONST_DISTANCE 的所有文档的一些过滤集。
一些谷歌搜索导致了一些潜在的起点( https://stackoverflow.com/a/45359952/8236733 和 https://firebase.google.com/docs/reference/js/firebase.database.Query#on ),但不太确定如何使用链接中显示的内容。任何有关如何实现这一目标的建议或文档将不胜感激。
最佳答案
无法将函数传递到 Cloud Firestore,然后使用它来过滤返回的文档。您要么需要传入静态值(例如您想要返回的纬度和经度),要么需要读取所有文档并使用客户端函数进行过滤。
您尝试执行的操作称为地理查询:根据文档到已知点的距离返回文档。不幸的是,该功能尚未内置到 Cloud Firestore 中,尽管它支持 geographical point data type 。您可以自己构建它,但您应该意识到目前此类查询效率相当低。
要了解更多信息:
- 一些开发者已将 Firebase 的 GeoFire 库移植到 Firestore。请参阅How to run a geo "nearby" query with firestore? ,
- 我不久前曾就此做过一次演讲,可在 YouTube 上观看:https://www.youtube.com/watch?v=mx1mMdHBi5Q
- AngularFirebase.com 还有一个页面 Realtime GeoQueries With Firestore
关于javascript - 如何使用函数过滤Firestore收集数据(用于位置距离过滤),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53607847/