我正在开发 React Native 应用程序,我正在从 firebase 集合中获取配置文件。 我想添加一个搜索功能,当我输入用户名的前 1 个或 2 个(或更多)字母并按下搜索按钮时。 我应该能够获取以这 1 或 2 个字母开头的用户名。
我确实检查了 Cloud Firestore 查询,但找不到适合我的问题的查询。
更新的问题:
在上面的代码中,我添加了 Renaud Tarnec 回答的以下代码。
let queries = hashes.map(hash => rangeQueryParams(hash))
.map(range => profiles.where('hash', '>=', range.start).where('hash', '<', range.end)
.orderBy('displayName') // displayName is the name of Field here
.startAt(searchString)
.endAt(searchString + '\uf8ff')
.get());
但这似乎行不通。我猜这是因为 range filter 和 orderBy
在这里位于不同的字段上。
最佳答案
您应该结合使用 orderBy()
、startAt()
和 endAt()
,请参阅此处的文档:https://firebase.google.com/docs/firestore/query-data/order-limit-data?authuser=0
var searchString = 'Sh' //Example of value
firebase
.firestore()
.collection('yourCollectioName')
.orderBy('username')
.startAt(searchString)
.endAt(searchString + '\uf8ff')
.get()
.then(...)
查询中使用的字符 \uf8ff
在 Unicode 中大多数常规字符之后,因此查询匹配所有以 searchString
开头的值。
关于firebase - 如何根据 Firestore 数据库中的字段从集合中搜索文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58364501/