【问题标题】:How do I filter data from cloud firestore twice?如何两次过滤来自 Cloud Firestore 的数据?
【发布时间】: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'.

有人可以帮助我实施我的计划吗? 也许整个事情必须以不同的方式完成?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore firebase-authentication flutter-test


    【解决方案1】:

    你没有对 where 语句的返回值做任何事情。 QuerySnapshot 类没有 .data 静态 getter。为了从 firestore 访问返回值,您需要执行以下操作:

    ...
    final snapshot = await userTodos.where('Stufe' is int).get();
    final data = snapshot.data;
    ...
    

    【讨论】:

    • 我已经按照你的方式改变了它,但数据仍然带有红色下划线。 >getter 'data' 没有为类型 'QuerySnapshot' 定义。
    【解决方案2】:

    对于这种情况,我发现将FlutterFire documentationFirestore 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>
    • 谢谢,很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2021-12-08
    • 2020-07-11
    • 1970-01-01
    • 2021-01-12
    • 2015-09-29
    相关资源
    最近更新 更多