如何基于Firestore数据库中的字段从集合中搜索文档? [英] How to search document(s) from a collection based on a Field in Firestore database?

查看:81
本文介绍了如何基于Firestore数据库中的字段从集合中搜索文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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()的组合,请参见此处的文档:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆