如何根据 Firestore 数据库中的字段从集合中搜索文档? [英] How to search document(s) from a collection based on a Field in Firestore database?
问题描述
我正在开发一个 React Native 应用程序,我正在从 firebase 集合中获取配置文件.我想添加一个搜索功能,当我输入用户名的前 1 个或 2 个(或更多)字母并按下搜索按钮时.我应该能够获取以 1 或 2 个字母开头的用户名.
I'm working on a React Native application and I'm fetching profiles from a firebase collection. And I want to add a search functionality where when I enter even the first 1 or 2 (or more) alphabets of a username and press the search button. I should be able to fetch usernames starting with those 1 or 2 alphabets.
我确实检查了 Cloud Firestore 查询,但找不到针对我的问题的查询.
I did check Cloud Firestore queries but couldn't find one for my problem.
更新的问题:
在上面的代码中,我添加了 Renaud Tarnec 回答的以下代码.
In the above code, I'm adding the below code as answered by 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());
但这似乎不起作用.我猜这是因为范围过滤器和 orderBy
在这里位于不同的字段上.
But this doesn't seems to work. I guess it's because range filter and orderBy
are on different fields here.
推荐答案
你应该结合使用 orderBy()
、startAt()
和 endAt()
,请参阅此处的文档:https://firebase.google.com/docs/firestore/query-data/order-limit-data?authuser=0
You should use a combination of orderBy()
, startAt()
and endAt()
, see the documentation here: 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
开头的值.
The character uf8ff
used in the query is after most regular characters in Unicode, therefore the query matches all values that start with searchString
.
这篇关于如何根据 Firestore 数据库中的字段从集合中搜索文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!