如何两次过滤来自 Cloud Firestore 的数据?
Posted
技术标签:
【中文标题】如何两次过滤来自 Cloud Firestore 的数据?【英文标题】:How do I filter data from cloud firestore twice? 【发布时间】:2021-11-24 15:42:06 【问题描述】:我想检查一个用户在他的文档中是否有一个带有任何数字的字符串'Level'。
级别:int
如果是这种情况,future 应该返回 true,否则返回 false。 这就是我正在尝试的代码:
class StufenService
String userID;
StufenService(this.userID);
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future checkIfStufeExists() async
await userTodos.where('Stufe' is int).get();
final data = QuerySnapshot.data.documents.where(userID);
if (data.exists)
return true;
else
return false;
首先,我过滤掉所有在其基于火的文档中具有 'Level': int 的用户。然后我想检查当前用户是否在用户中。
QuerySnapshot 后面的数据是红色下划线的:
The getter 'data' isn't defined for the type 'QuerySnapshot'.
有人可以帮助我实施我的计划吗? 也许整个事情必须以不同的方式完成?
【问题讨论】:
【参考方案1】:你没有对 where 语句的返回值做任何事情。 QuerySnapshot 类没有 .data 静态 getter。为了从 firestore 访问返回值,您需要执行以下操作:
...
final snapshot = await userTodos.where('Stufe' is int).get();
final data = snapshot.data;
...
【讨论】:
我已经按照你的方式改变了它,但数据仍然带有红色下划线。 >getter 'data' 没有为类型 'QuerySnapshot【参考方案2】:对于这种情况,我发现将FlutterFire documentation 和Firestore reference 放在手边最有用。基于这些,你的代码应该是这样的:
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future checkIfStufeExists() async
var query = userTodos.where('Stufe', isEqualTo: 42); // First condition
query = query.where("userId", isEqualTo: userID); // Second condition
final querySnapshot = await query.get(); // Read from the database
return querySnapshot.size > 0; // Check if there are any results
【讨论】:
是的。我总是建议在返回类型中更明确,所以说Future<bool>
。
谢谢,很有帮助!以上是关于如何两次过滤来自 Cloud Firestore 的数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何将来自不同组件的 firebase auth 和 Cloud Firestore 用作单个 Firebase 应用程序
如何在颤动的社交媒体应用程序中过滤出匹配的用户名来自 Firestore 数据库