如何根据 Firestore 数据库中的字段从集合中搜索文档?

Shu*_*sht 2 firebase google-cloud-platform react-native firebase-realtime-database google-cloud-firestore

我正在开发一个 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());
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。我想这是因为范围过滤器 和orderBy在这里位于不同的字段。

Ren*_*nec 8

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(...)
Run Code Online (Sandbox Code Playgroud)

查询中使用的字符\uf8ff位于 Unicode 中大多数常规字符之后,因此查询匹配以 开头的所有值searchString